async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Front-end asynchronous features proposed in ES7 (ES2017): async, await.
async and await are new contents in ES7. For solutions to asynchronous operations, async/await can be said to be the co module and generation Syntactic sugar for device functions. Solve js asynchronous code with clearer semantics.
async, as the name suggests, means "asynchronous". async is used to declare that a function is asynchronous. And await literally means "waiting", which is used to wait for asynchronous completion.
Async and await have a strict rule. Both cannot be separated from each other. However, await can only be written in the async function.
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.
Let’s use a simple example to compare the similarities, differences, and trade-offs between the three methods.
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.
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); })
The then() method of Promise can return another Promise or a synchronized value. If a synchronized value is returned, 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 it. 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 does it mean, that is, 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); })
Here we nest two Promise, so that in the last query operation, we can call the outside 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.
Another way 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); });
In the return of each then() method, we pass the db and its Each time the other results form an object 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().
这种方式,也是很蛋疼的一个方式,因为如果遇到then()方法中返回的不是同步的值,而是Promise的话,我们需要多做很多工作。而且,每次都透传一个“多余”的db对象,在逻辑上也有点冗余。
但除此之外,对于Promise链的使用,如果遇到上面的问题,好像也没其他更好的方法解决了。我们只能根据场景去选择一种“最优”的方案,如果要使用Promise链的话。
鉴于Promise上面蛋疼的问题,TJ大神将ES6中的生成器函数,用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); });
co是一个函数,将接受一个生成器函数作为参数,去执行这个生成器函数。生成器函数中使用yield
关键字来“同步”获取每个异步操作的值。
上面代码在代码形式上,比上面使用Promise链要优雅,我们消灭了回调函数,代码看起来都是同步的。除了使用co和yield有点怪之外。
使用co模块,我们要将所有的操作包装成一个生成器函数,然后使用co()去调用这个生成器函数。看上去也还可以接受,但是ES的进化是不满足于此的,于是async/await被提到了ES7的提案。
我们先看一下使用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); });
我们对比代码可以看出,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); })
我们定义getBlogs为一个async函数,最后返回得到的博客列表最终会被包装成一个Promise返回,如上,我们直接调用getBlogs().then()方法可获取async函数返回值。
好了,上面我们简单对比了一下三种解决异步方案,下面我们来深入了解一下async/await。
async用于定义一个异步函数,该函数返回一个Promise。
如果async函数返回的是一个同步的值,这个值将被包装成一个理解resolve的Promise,等同于return Promise.resolve(value)
。
await用于一个异步操作之前,表示要“等待”这个异步操作的返回值。await也可以用于一个同步的值。
//返回一个Promise let timer = async function timer(){ return new Promise((resolve,reject) => { setTimeout(() => { resolve('500'); },500); }); } timer().then(result => { console.log(result); //500 }).catch(err => { console.log(err.message); });
//返回一个同步的值 let sayHi = async function sayHi(){ let hi = await 'hello world'; return hi; //等同于return Promise.resolve(hi); } sayHi().then(result => { console.log(result); });
上面这个例子返回是一个同步的值,字符串’hello world’,sayHi()是一个async函数,返回值被包装成一个Promise,可以调用then()方法获取返回值。对于一个同步的值,可以使用await,也可以不使用await。效果效果是一样的。具体用不用,看情况。
比如上面使用mongodb查询博客那个例子,let coll = db.collection('blogs');
,这里我们就没有用await,因为这是一个同步的值。当然,也可以使用await,这样会显得代码统一。虽然效果是一样的。
let sayHi = async function sayHi(){ throw new Error('出错了'); } sayHi().then(result => { console.log(result); }).catch(err => { console.log(err.message); //出错了 });
我们直接在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 //故意抛出错误
如上面的代码,定义两个异步操作,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); });
我们将count()和list()使用Promise.all()“同时”执行,这里count()和list()可以看作是“并行”执行的,所耗时间将是两个异步操作中耗时最长的耗时。
The final result is an array composed of the results of the two operations. We just need to take out the values in the array in order.
[Recommended learning: javascript video tutorial]
The above is the detailed content of Is async for es6 or es7?. For more information, please follow other related articles on the PHP Chinese website!