search

Home  >  Q&A  >  body text

javascript - What does it mean to write asynchronously in synchronous way?

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

天蓬老师天蓬老师2727 days ago1130

reply all(4)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-07-05 10:54:36

    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 the done() callback to handle things after the call is completed. But actually it also has standard Promise's then(), so the above done can be changed to then, but be aware that done registers a callback in the form of an event, and it returns the current Promise object itself , several callbacks can be registered in chain calls. And then returns 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

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 10:54:36

    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.

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-07-05 10:54:36

    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();

    f is an asynchronous operation. If you do not use async/await and print t directly synchronously, the result will definitely be undefined; 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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-07-05 10:54:36

    The two answers above are enough

    reply
    0
  • Cancelreply