ES6 - anync

时间:2021-02-08 12:36:23   收藏:0   阅读:0

1.含义

async函数简洁点说就是Generator函数的语法糖。

示例:一个读取文件的异步操作,逐步执行,使用Generator函数执行

 1     const fs = require(‘fs‘)
 2 
 3     const readFile = function (fileName) {
 4         return new Promise(function (resolve, reject) {
 5             fs.readFile(fileName, function (error, data) {
 6                 if (error) return reject(error);
 7                 resolve(data);
 8             });
 9         })
10     }
11 
12     const gen = function* (){
13         const f1 = yield readFile(‘./a‘)
14         const f2 = yield readFile(‘./b‘)
15         console.log("文件读取结束");
16     }

 使用async函数执行

1     const gen = async function (){
2         const f1 = await readFile(‘./a‘)
3         const f2 = await readFile(‘./b‘)
4         console.log("文件读取结束");
5     }

 

可以看到,async函数就是将Generate函数的星号(*)替换成async,将yield替换为await而已。

async函数对Generator函数的改进体现在以下四点:

2.基本用法

 

 

 

 

 

 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!