Home > Web Front-end > JS Tutorial > Detailed explanation of async/await usage examples of ES7

Detailed explanation of async/await usage examples of ES7

巴扎黑
Release: 2017-09-11 10:35:12
Original
1726 people have browsed it

This article mainly introduces the in-depth understanding of the usage of async/await in ES7. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

When I first learned about ES6 Promise, I wrote a blog post "Comparison of promise and co with generator function to solve the asynchronous process of js code". The comparison in the article In order to use Promise and co modules with generator functions to solve the similarities and differences of js asynchronous.

At the end of the article, ES7’s async and await were mentioned, but they were only mentioned briefly at the time and were not discussed in depth.

In the Nodejs V7 released two months ago, support for async and await has been added. Today, let’s do an in-depth exploration of this stuff. Write asynchronous code in a more elegant way.

What is async/await

async/await can be said to be syntactic sugar for co modules and generator functions. Solve js asynchronous code with clearer semantics.

Students who are familiar with the co module should know that the co module is a module written by Master TJ that uses a generator function to solve asynchronous processes. It can be regarded as the executor of the generator function. Async/await is an upgrade to the co module. It has a built-in generator function executor and no longer relies on the co module. At the same time, async returns Promise.

From the above point of view, whether it is the co module or async/await, Promise is used as the most basic unit. Students who do not know much about Promise can first learn more about Promise.

Compare Promise, co, async/await

Let’s use a simple example to compare the similarities and differences of the three methods, and Trade-offs.

We use mongodb's nodejs driver to query the mongodb database as an example. The reason is that mongodb's js driver has implemented returning Promise by default, and we do not need to wrap Promise separately.

Use Promise chain


MongoClient.connect(url + db_name).then(db=> {
  return db.collection('blogs');
}).then(coll=> {
  return coll.find().toArray();
}).then(blogs=> {
  console.log(blogs.length);
}).catch(err=> {
  console.log(err);
})
Copy after login

The then() method of Promise can return another Promise or a synchronized value , if a synchronized value is returned, it will be wrapped into a Promise.

In the above example, db.collection() will return a synchronized value, that is, a collection object, but it will be wrapped into a Promise and will be transparently passed to the next then() method.

The above example uses a Promise chain.

First connect to the database MongoClient.connect() returns a Promise, then obtain the database object db in the then() method, and then obtain the coll object and return. Obtain the coll object in the next then() method, then perform a query, return the query results, and call the then() method layer by layer to form a Promise chain.

In this Promise chain, if an exception occurs in any link, it will be caught by the final catch().

It can be said that this code written using Promise chain is more elegant and the process is clearer than calling callback functions layer by layer. First get the database object, then get the collection object, and finally query the data.

But there is a not very "elegant" problem here, which is that the object obtained by each then() method is the data returned by the previous then() method. It cannot be accessed across layers.

What it means is that in the third then (blogs => {}) we can only get the query result blogs, but cannot use the above db object and coll object. At this time, what if you want to close the database db.close() after printing out the blogs list?

At this time, there are two solutions:

The first is to use then() nesting. We break the Promise chain and make it nested, just like using the nesting of callback functions:


MongoClient.connect(url + db_name).then(db=> {
  let coll = db.collection('blogs');
  coll.find().toArray().then(blogs=> {
    console.log(blogs.length);
    db.close();
  }).catch(err=> {
    console.log(err);
  });
}).catch(err=> {
  console.log(err);
})
Copy after login

Here we nest two Promise, so that in the last one In the query operation, you can call the external db object. However, this method is not recommended. The reason is simple, we went from one kind of callback function hell to another kind of Promise callback hell.

Moreover, we need to catch the exception of each Promise, because Promise does not form a chain.

There is another way, which is to pass the db in each then() method:


MongoClient.connect(url + db_name).then(db=> {
  return {db:db,coll:db.collection('blogs')};
}).then(result=> {
  return {db:result.db,blogs:result.coll.find().toArray()};
}).then(result=> {
  return result.blogs.then(blogs=> {  //注意这里,result.coll.find().toArray()返回的是一个Promise,因此这里需要再解析一层
    return {db:result.db,blogs:blogs}
  })
}).then(result=> {
  console.log(result.blogs.length);
  result.db.close();
}).catch(err=> {
  console.log(err);
});
Copy after login

We pass the db in each then() method: In the return, db and its other results each time are composed into an object and returned. Please note that it is okay if each result is a synchronized value, but if it is a Promise value, each Promise requires an additional layer of parsing.

For example, in the above example, in the {db:result.db,blogs:result.coll.find().toArray()} object returned by the second then() method, blogs is a Promise. In the next then() method, we cannot directly reference the blog list array value, so we need to call the then() method to parse one layer first, and then return the two synchronized values ​​db and blogs.

Note that this involves the nesting of Promise, but a Promise only nests one level of then().

This method is also a very painful method, because if the then() method returns not a synchronized value but a Promise, we need to do a lot more work. Moreover, transparently transmitting an "extra" db object every time is a bit redundant logically.

但除此之外,对于Promise链的使用,如果遇到上面的问题,好像也没其他更好的方法解决了。我们只能根据场景去选择一种“最优”的方案,如果要使用Promise链的话。

鉴于Promise上面蛋疼的问题,TJ大神将ES6中的生成器函数,用co模块包装了一下,以更优雅的方式来解决上面的问题。

co搭配生成器函数

如果使用co模块搭配生成器函数,那么上面的例子可以改写如下:


const co = require('co');
co(function* (){
  let db = yield MongoClient.connect(url + db_name);
  let coll = db.collection('blogs');
  let blogs = yield coll.find().toArray();
  console.log(blogs.length);
  db.close();
}).catch(err=> {
  console.log(err);
});
Copy after login

co是一个函数,将接受一个生成器函数作为参数,去执行这个生成器函数。生成器函数中使用 yield 关键字来“同步”获取每个异步操作的值。

上面代码在代码形式上,比上面使用Promise链要优雅,我们消灭了回调函数,代码看起来都是同步的。除了使用co和yield有点怪之外。

使用co模块,我们要将所有的操作包装成一个生成器函数,然后使用co()去调用这个生成器函数。看上去也还可以接受,但是ES的进化是不满足于此的,于是async/await被提到了ES7的提案。

async/await

我们先看一下使用async/await改写上面的代码:


(async function(){
  let db = await MongoClient.connect(url + db_name);
  let coll = db.collection('blogs');
  let blogs = await coll.find().toArray();
  console.log(blogs.length);
  db.close();
})().catch(err=> {
  console.log(err);
});
Copy after login

我们对比代码可以看出,async/await和co两种方式代码极为相似。

co换成了async,yield换成了await。同时生成器函数变成了普通函数。

这种方式在语义上更加清晰明了,async表明这个函数是异步的,同时await表示要“等待”异步操作返回值。

async函数返回一个Promise,上面的代码其实是这样:


let getBlogs = async function(){
  let db = await MongoClient.connect(url + db_name);
  let coll = db.collection('blogs');
  let blogs = await coll.find().toArray();
  db.close();
  return blogs;
};

getBlogs().then(result=> {
  console.log(result.length);
}).catch(err=> {
  console.log(err);
})
Copy after login

我们定义getBlogs为一个async函数,最后返回得到的博客列表最终会被包装成一个Promise返回,如上,我们直接调用getBlogs().then()方法可获取async函数返回值。

好了,上面我们简单对比了一下三种解决异步方案,下面我们来深入了解一下async/await。

深入async/await

async返回值

async用于定义一个异步函数,该函数返回一个Promise。

如果async函数返回的是一个同步的值,这个值将被包装成一个理解resolve的Promise,等同于return Promise.resolve(value)

await用于一个异步操作之前,表示要“等待”这个异步操作的返回值。await也可以用于一个同步的值。


//返回一个Promise
let timer = async functiontimer(){
  return new Promise((resolve,reject) => {
    setTimeout(()=> {
      resolve('500');
    },500);
  });
}

timer().then(result=> {
 console.log(result); //500
}).catch(err=> {
  console.log(err.message);
});
Copy after login


//返回一个同步的值
let sayHi = async functionsayHi(){
 let hi = await 'hello world';  
 return hi; //等同于return Promise.resolve(hi);
}

sayHi().then(result=> {
 console.log(result);
});
Copy after login

上面这个例子返回是一个同步的值,字符串'hello world',sayHi()是一个async函数,返回值被包装成一个Promise,可以调用then()方法获取返回值。

对于一个同步的值,可以使用await,也可以不使用await。效果效果是一样的。具体用不用,看情况。

比如上面使用mongodb查询博客那个例子, let coll = db.collection('blogs'); ,这里我们就没有用await,因为这是一个同步的值。当然,也可以使用await,这样会显得代码统一。虽然效果是一样的。

async函数的异常


let sayHi = async functionsayHi(){
  throw new Error('出错了');
}
sayHi().then(result=> {
 console.log(result);
}).catch(err=> {
  console.log(err.message);  //出错了
});
Copy after login

我们直接在async函数中抛出一个异常,由于返回的是一个Promise,因此,这个异常可以调用返回Promise的catch()方法捕捉到。

和Promise链的对比:

我们的async函数中可以包含多个异步操作,其异常和Promise链有相同之处,如果有一个Promise被reject()那么后面的将不会再进行。


let count = ()=>{
  return new Promise((resolve,reject) => {
    setTimeout(()=>{
      reject('故意抛出错误');
    },500);
  });
}

let list = ()=>{
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      resolve([1,2,3]);
    },500);
  });
}

let getList = async ()=>{
  let c = await count();
  let l = await list();
  return {count:c,list:l};
}
console.time('begin');
getList().then(result=> {
  console.log(result);
}).catch(err=> {
  console.timeEnd('begin');
  console.log(err);
});
//begin: 507.490ms
//故意抛出错误
Copy after login

如上面的代码,定义两个异步操作,count和list,使用setTimeout延时500毫秒,count故意直接抛出异常,从输出结果来看,count()抛出异常后,直接由catch()捕捉到了,list()并没有继续执行。

并行

使用async后,我们上面的例子都是串行的。比如上个list()和count()的例子,我们可以将这个例子用作分页查询数据的场景。

先查询出数据库中总共有多少条记录,然后再根据分页条件查询分页数据,最后返回分页数据以及分页信息。

我们上面的例子count()和list()有个“先后顺序”,即我们先查的总数,然后又查的列表。其实,这两个操作并无先后关联性,我们可以异步的同时进行查询,然后等到所有结果都返回时再拼装数据即可。


let count = ()=>{
  return new Promise((resolve,reject) => {
    setTimeout(()=>{
      resolve(100);
    },500);
  });
}

let list = ()=>{
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      resolve([1,2,3]);
    },500);
  });
}

let getList = async ()=>{
  let result = await Promise.all([count(),list()]);
  return result;
}
console.time('begin');
getList().then(result=> {
  console.timeEnd('begin'); //begin: 505.557ms
  console.log(result);    //[ 100, [ 1, 2, 3 ] ]
}).catch(err=> {
  console.timeEnd('begin');
  console.log(err);
});
Copy after login

我们将count()和list()使用Promise.all()“同时”执行,这里count()和list()可以看作是“并行”执行的,所耗时间将是两个异步操作中耗时最长的耗时。

最后得到的结果是两个操作的结果组成的数组。我们只需要按照顺序取出数组中的值即可。

JavaScript 中最蛋疼的事情莫过于回调函数嵌套问题。以往在浏览器中,因为与服务器通讯是一种比较昂贵的操作,因此比较复杂的业务逻辑往往都放在服务器端,前端 JavaScript 只需要少数几次 AJAX 请求就可拿到全部数据。

但是到了 webapp 风行的时代,前端业务逻辑越来越复杂,往往几个 AJAX 请求之间互有依赖,有些请求依赖前面请求的数据,有些请求需要并行进行。还有在类似 Node.js 的后端 JavaScript 环境中,因为需要进行大量 IO 操作,问题更加明显。这个时候使用回调函数来组织代码往往会导致代码难以阅读。

现在比较流行的解决这个问题的方法是使用 Promise,可以将嵌套的回调函数展平。但是写代码和阅读依然有额外的负担。

另外一个方案是使用 ES6 中新增的 generator,因为 generator 的本质是可以将一个函数执行暂停,并保存上下文,再次调用时恢复当时的状态。co 模块是个不错的封装。但是这样略微有些滥用 generator 特性的感觉。

ES7 中有了更加标准的解决方案,新增了 async/await 两个关键词。async 可以声明一个异步函数,此函数需要返回一个 Promise 对象。await可以等待一个 Promise 对象 resolve,并拿到结果。

比如下面的例子,以往我们无法在 JavaScript 中使用常见的 sleep 函数,只能使用 setTimeout 来注册一个回调函数,在指定的时间之后再执行。有了 async/await 之后,我们就可以这样实现了:


async function sleep(timeout) {
 return new Promise((resolve, reject) => {
  setTimeout(function() {
   resolve();
  }, timeout);
 });
}

(async function() {
 console.log('Do some thing, ' + new Date());
 await sleep(3000);
 console.log('Do other things, ' + new Date());
})();
Copy after login

执行此段代码,可以在终端中看到结果:

Do some thing, Mon Feb 23 2015 21:52:11 GMT+0800 (CST)
Do other things, Mon Feb 23 2015 21:52:14 GMT+0800 (CST)

另外 async 函数可以正常的返回结果和抛出异常。await 函数调用即可拿到结果,在外面包上 try/catch 就可以捕获异常。下面是一个从豆瓣 API 获取数据的例子:


var fetchDoubanApi = function() {
 return new Promise((resolve, reject) => {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
   if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 300) {
     var response;
     try {
      response = JSON.parse(xhr.responseText);
     } catch (e) {
      reject(e);
     }
     if (response) {
      resolve(response, xhr.status, xhr);
     }
    } else {
     reject(xhr);
    }
   }
  };
  xhr.open(&#39;GET&#39;, &#39;https://api.douban.com/v2/user/aisk&#39;, true);
  xhr.setRequestHeader("Content-Type", "text/plain");
  xhr.send(data);
 });
};

(async function() {
 try {
  let result = await fetchDoubanApi();
  console.log(result);
 } catch (e) {
  console.log(e);
 }
})();
Copy after login

async 函数的用法

同 Generator 函数一样,async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再接着执行函数体内后面的语句。
下面是一个例子。


async function getStockPriceByName(name) {
 var symbol = await getStockSymbol(name);
 var stockPrice = await getStockPrice(symbol);
 return stockPrice;
}

getStockPriceByName(&#39;goog&#39;).then(function (result){
 console.log(result);
});
Copy after login

阅读本文前,期待您对promise和ES6(ECMA2015)有所了解,会更容易理解。本文以体验为主,不会深入说明,结尾有详细的文章引用。

第一个例子

Async/Await应该是目前最简单的异步方案了,首先来看个例子。这里我们要实现一个暂停功能,输入N毫秒,则停顿N毫秒后才继续往下执行。


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

var start = async function () {
  // 在这里使用起来就像同步代码那样直观
  console.log(&#39;start&#39;);
  await sleep(3000);
  console.log(&#39;end&#39;);
};

start();
Copy after login

控制台先输出start,稍等3秒后,输出了end。

基本规则

async 表示这是一个async函数,await只能用在这个函数里面。await表示在这里等待promise返回结果了,再继续执行。await 后面跟着的应该是一个promise对象(当然,其他返回值也没关系,只是会立即执行,不过那样就没有意义了…)

获得返回值

await等待的虽然是promise对象,但不必写.then(..),直接可以得到返回值。


var sleep = function (time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      // 返回 ‘ok&#39;
      resolve(&#39;ok&#39;);
    }, time);
  })
};

var start = async function () {
  let result = await sleep(3000);
  console.log(result); // 收到 ‘ok&#39;
};
Copy after login

捕捉错误

既然.then(..)不用写了,那么.catch(..)也不用写,可以直接用标准的try catch语法捕捉错误。


var sleep = function (time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      // 模拟出错了,返回 ‘error&#39;
      reject(&#39;error&#39;);
    }, time);
  })
};

var start = async function () {
  try {
    console.log(&#39;start&#39;);
    await sleep(3000); // 这里得到了一个返回错误
    
    // 所以以下代码不会被执行了
    console.log(&#39;end&#39;);
  } catch (err) {
    console.log(err); // 这里捕捉到错误 `error`
  }
};
Copy after login

循环多个await

await看起来就像是同步代码,所以可以理所当然的写在for循环里,不必担心以往需要闭包才能解决的问题。


..省略以上代码
var start = async function () {
  for (var i = 1; i <= 10; i++) {
    console.log(`当前是第${i}次等待..`);
    await sleep(1000);
  }
};
Copy after login

值得注意的是,await必须在async函数的上下文中的。


..省略以上代码

let one2ten = [1,2,3,4,5,6,7,8,9,10];

// 错误示范
one2ten.forEach(function (v) {
  console.log(`当前是第${v}次等待..`);
  await sleep(1000); // 错误!! await只能在async函数中运行
});

// 正确示范
for(var v of one2ten) {
  console.log(`当前是第${v}次等待..`);
  await sleep(1000); // 正确, for循环的上下文还在async函数中
}
Copy after login

The above is the detailed content of Detailed explanation of async/await usage examples of ES7. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template