es6+最佳入门实践(11)
11.async函数
async 函数是什么?一句话,它就是 Generator 函数的语法糖。通俗的说就是Generator函数的另一种写法,这种写法更简洁,除此之外,async函数还对Genrator进行了一些改进
首先,来回顾一下Generator函数实现文件读取
const fs = require('fs');
const co = require('co');
function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
function* asyncFile() {
let a = yield readFile('a.txt');
let b = yield readFile('b.txt');
let c = yield readFile('c.txt');
console.log(a.toString(), b.toString(), c.toString())
}
let gen = asyncFile();
gen.next().value.then((data)=>{
console.log(data.toString());
return gen.next().value;
}).then((data2)=>{
console.log(data2.toString());
return gen.next().value;
}).then((data3)=>{
console.log(data3.toString())
});
如果使用async函数的写法如下:
async function asyFile() {
let a = await readFile('a.txt');
let b = await readFile('b.txt');
let c = await readFile('c.txt');
console.log(a.toString());
console.log(b.toString());
console.log(c.toString());
}
asyFile()
比较后发现,async函数就是将 Generator 函数的星号(*)替换成async,将yield替换成await,仅此而已,实际上async函数做了一些改进的,例如:内置了自动执行器,不需要再引入co模块了