To understand the asynchronous operation of the async ES7 / await

1. What is async, await?

async suggests that it is "asynchronous" means, async is used to declare a function is asynchronous. And await literally means "wait" means, is waiting for the asynchronous completion. Async and await only be used in the function.

Usually async, await follow Promise are used together. Why do you say? Because the object is a Promise while async async returned on any suitable type of function. Such await result is a Promise objects (if not the object, then it async Promise to return what it is);

After getting await Promise objects Promise to wait for the next resolve or reject.

We look at an example:

. 1  var SLEEP = function (Time) {
 2      return  new new Promise ( function (Resolve, Reject) {
 . 3          the setTimeout ( function () {
 . 4              Resolve ();
 . 5          }, Time);
 . 6      })
 . 7  };
 . 8  
. 9  var Start = the async function () {
 10      // here to use as intuitive as the synchronization code 
. 11      the console.log ( 'Start' );
 12 is      the await SLEEP (3000 );
 13 is      the console.log ( 'End' );
14 };
15 
16 start();

 Results console running the above code: prints out 'start', and then waits for 3 seconds to print out "end", this is a simple example of async / await the.

2, we need to know is:

1 1 , async indicates that this is a async function, await only be used in this function inside.
2  
. 3 2, the async / the await asynchronous code is a new method of preparation. Before the asynchronous callback program code and promise.
. 4  
. 5 . 3, the async / the await is based on the promise.
6     followed behind await a promise should be the object (of course, other return value does not matter, but will be executed immediately, but that does not make sense ...),
 7     await represents the promise to return here to wait for the results, and then continue.
8  
9 4, the async / the await as promise, just as non-blocking.
10  
11 5, the async / asynchronous make the await code look, behave more like synchronous code. This is the true power of async / await, but also can be said that compared to the promise of the biggest advantages.

3, first understand what role async function

 

1 async function test() {
2   return "hello world";
3 }
4 
5 const result = test();
6 console.log(result);

 

Browser print out is: Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "hello world"}

Think about if async function does not return value it? Look like? The following code:

1 async function test() {
2  console.log("111111111")
3 }
4 
5 const result = test();
6 console.log(result);

Browser print results are as follows:
'111111111'
Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: undefined}
That is returned result is Promise.resolve (undefined)

See here understand me? async function returns a Promise object. This means that if we return async function in a constant, this constant will async by Promise.resolve () Promise encapsulated object.

Since it is a Promise objects, then we can also get their value by then () method, as follows

test().then(res => {
    console.log(res);    // 输出 hello world
});

Read the above code is not very clear async / await dim in the end?

We know the characteristics of Promise - no wait, so perform async function without await the circumstances, it would be executed immediately return a Promise object, and will not be blocked behind the statement. This general object Promise function returns no different.

Then the next key point is that await the keyword.

4, await dim, what has been done?

Generally await operator is waiting for a Promise object. It can only be used in asynchronous function async function. But the fact is that after await a Promise can be any object or value to wait. See: the await grammar .

If a Promise is passed to await an operator, will wait Promise await normal processing is complete and returns the processing result

function test(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await test(10);
  console.log(x); // 10
}
f1();

If the value is not a Promise, await will convert this value as the normal processing Promise, then wait for the processing result.

async function f2() {
  var y = await 20;
  console.log(y); // 20
}
f2();

If the Promise handle the exception, the exception value is thrown.

async function f3() {
  try {
    var z = await Promise.reject(30);
  } catch (e) {
    console.log(e); // 30
  }
}
f3();

5, the advantages of async / await then that the processing chain of

This is using async / await the most advantageous place

Promise a single chain does not discover the advantages async / await, but if you need time to deal with then chain composed of a plurality of Promise, benefits can be manifested (in fact, Promise to solve the problem of multi-layered callback chain by then, and now with the async / await further optimize it, it can be said async / await based Promise to do better deal)

Assuming a service, is completed in several steps, each step are asynchronous, but also on the result of the last step. We still use setTimeout to simulate asynchronous operation:

This code is copied below paragraphs case of the Internet, can explain the problem on the line.
/**
 * 传入参数 n,表示这个函数执行的时间(毫秒)
 * 执行的结果是 n + 200,这个值将用于下一步骤
 */
function takeLongTime(n) {
    return new Promise(resolve => {
        setTimeout(() => resolve(n + 200), n);
    });
}

function step1(n) {
    console.log(`step1 with ${n}`);
    return takeLongTime(n);
}

function step2(n) {
    console.log(`step2 with ${n}`);
    return takeLongTime(n);
}

function step3(n) {
    console.log(`step3 with ${n}`);
    return takeLongTime(n);
}

现在用 Promise 方式来实现这三个步骤的处理

function doIt() {
    console.time("doIt");
    const time1 = 300;
    step1(time1)
        .then(time2 => step2(time2))
        .then(time3 => step3(time3))
        .then(result => {
            console.log(`result is ${result}`);
            console.timeEnd("doIt");
        });
}

doIt();

// c:\var\test>node --harmony_async_await .
// step1 with 300
// step2 with 500
// step3 with 700
// result is 900
// doIt: 1507.251ms

输出结果 result 是 step3() 的参数 700 + 200 = 900。doIt() 顺序执行了三个步骤,一共用了 300 + 500 + 700 = 1500 毫秒,和 console.time()/console.timeEnd() 计算的结果一致。

如果用 async/await 来实现呢,会是这样

async function doIt() {
    console.time("doIt");
    const time1 = 300;
    const time2 = await step1(time1);
    const time3 = await step2(time2);
    const result = await step3(time3);
    console.log(`result is ${result}`);
    console.timeEnd("doIt");
}

doIt();

结果和之前的 Promise 实现是一样的,但是这个代码看起来是不是清晰得多,几乎跟同步代码一样。

关于async/await 处理 then 链,网上有很多文章,可以搜搜,基本可以理解的差不多。

 

 

 

总结参考文章:https://www.jianshu.com/p/5cae46133bad

function  takeLongTime( n) {
     return  new  Promise( resolve  => {
         setTimeout(()  =>  resolve(n  +  200), n);
    });
}

Guess you like

Origin www.cnblogs.com/mahmud/p/11518475.html