javascript - What does it mean to write asynchronously in synchronous way?
天蓬老师
天蓬老师 2017-07-05 10:52:36
0
4
1055

Isn’t synchronization just synchronization, and isn’t asynchronous just asynchronous? What does it mean to write asynchronously in a synchronous way?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all (4)
扔个三星炸死你

Asynchronous calls are non-blocking for the current thread, so if you want to know whether the asynchronous processing is completed or whether an error occurred, it is usually achieved through events or callbacks, which are common in Node.js. Ajax is a very typical asynchronous call, take jQuery.ajax as an example

$.getJSON("http://api.youapp.com/resouce1") .done(function(jo) { console.log("api resouce1 返回的是", jo); });

jQuery's Ajax returns jQuery's Promise object. Generally, we will use thedone()callback to handle things after the call is completed. But actually it also has standard Promise'sthen(), so the abovedonecan be changed tothen, but be aware thatdoneregisters a callback in the form of an event, and it returns the current Promise object itself , several callbacks can be registered in chain calls. Andthenreturns another Promise object (standard Promise specification). If called in a chain, each call does not act on the same Promise object.

If you need to make another asynchronous call in a callback, you need to register another callback in the callback. For example, to obtain certain data, you need to first obtain a certain value from api1, then use this value to obtain a certain resource from api2, and then use a certain value in this resource to obtain this value from api3. Such a callback would look like this when written. :

$.getJSON("http://api.youapp.com/resouce1") .then(function(jo) { $.getJSON("http://api.youapp.com/resouce2?id=" + jo.blaId) .then(function(jo2) { $.getJSON("http://api.youapp.com/resouce3?xxx=" + jo2.xxxValue) .then(function(value) { console.log("总算拿到了", value); }); }); });

This is only the third level... a very scary form. This form is called "callback hell."

Everyone has thought of many ways to solve this problem, and Promise is one of them, but Promise still cannot completely get rid of this form. The co library is also one of the solutions, but it cannot be completely eliminated.

However, ES2017 introduced async/await, which is the so-called asynchronous writing in a synchronous form. For example, the above code can be rewritten as

async function xxx() { const jo = await $.getJSON("http://api.youapp.com/resouce1"); const jo2 = await $.getJSON("http://api.youapp.com/resouce2?id=" + jo.blaId); const value = await $.getJSON("http://api.youapp.com/resouce3?xxx=" + jo2.xxxValue); console.log("总算拿到了", value); }

async/await eliminates callbacks, so it looks the same as writing non-asynchronous (that is, synchronous) code.

Reference:

  • Talk about the “flattening” of asynchronous calls

  • From hell to heaven, Node callback changes to async/await

  • Understand JavaScript’s async/await

    Ty80

    It is common to nest callback functions when asynchronous, in the form of:

    // 先读取 a fs.readFile('a.txt', (a) => { // a 读取成功后读取 b fs.readFile('b.txt', (b) => { // b 读取成功后读取 c fs.readFile('c.txt'. (c) => { console.log(a + b + c) }) }) })

    At this time, callback nesting appears, which needs to be nested layer by layer, which is very error-prone and difficult to maintain.

    Writing asynchronously in synchronous mode is similar to:

    function * asyncWrapper () { const a = yield read('a.txt') const b = yield read('b.txt') const c = yield read('c.txt') console.log(a + b + c) } // 使用形如 co 的库自动执行异步逻辑 co(asyncWrapper)

    At this time, the asynchronous business logic is implemented through normal synchronization.

      我想大声告诉你

      Writing asynchronously in synchronous way refers to the organization form of the code. You can use async/await to write asynchronously in a synchronous manner, see the following code:

      const testAsync = async () => { const t = await f(); console.log(t); }; testAsync();

      fis an asynchronous operation. If you do not use async/await and print t directly synchronously, the result will definitely beundefined; after using async/await, the code still looks synchronous in form, but the asynchronous execution is performed first. Operate f, and then print t’s

        伊谢尔伦

        The two answers above are enough

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!