Async Await use

1. Simple example

var sleep = function (time) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, time); }) };

var start = async function () { // It's as intuitive to use as synchronous code here 
    console.log('start' ); await sleep(3000); console.log('end'); };
 start();

The console outputs first start, and 3秒after a while, it outputs end.

2. Basic Rules

  1. async means 这是一个async函数, await只能用在这个函数里面.
  2. await means here 等待promise返回结果, and then continue to execute.
  3. await followed by 应该是一个promise对象(of course, other return values ​​are fine, just executed immediately, but that would be pointless...)

3、

await must appear in the code marked with async, indicating that a piece of thread code is suspended later, and the code after await asynchronous code indicates callback code .

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324488218&siteId=291194637