JavaScript异步编程解决方案Promise、Generator、Async
下面通过按顺序读取本地文件data/1.txt-->data/2.txt-->data/3.txt三个问题来介绍三者的使用方式和差别
1,使用Promise实现
const fs = require('fs'); function readFile(filename) { return new Promise((resolve, reject) => { fs.readFile(filename, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } readFile('data/1.txt').then(res => { console.log(res.toString()); return readFile('data/2.txt'); }).then(res => { console.log(res.toString()); return readFile('data/3.txt'); }).then(res => { console.log(res.toString()); });
2,使用Generator的方式实现
const fs = require('fs'); function readfile(pathname) { return new Promise((resolve, reject) => { fs.readFile(pathname, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } function* gen() { yield readfile('data/1.txt'); yield readfile('data/2.txt'); yield readfile('data/3.txt'); } let g1 = gen(); g1.next().value.then(res => { console.log(res.toString()); return g1.next().value; }).then(res => { console.log(res.toString()); return g1.next().value; }).then(res => { console.log(res.toString()); });
3,使用Async的方式实现
const fs = require('fs'); function readfile(pathname) { return new Promise((resolve, reject) => { fs.readFile(pathname, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } async function asy() { let a = await readfile('data/1.txt'); let b = await readfile('data/2.txt'); let c = await readfile('data/3.txt'); console.log(a.toString(), b.toString(), c.toString()); } asy();
async特点
1,await要放在async函数体中
2,比generator更加语义化
3,await后面可以是promise对象,也可以是数字,字符串和布尔值
4,只要await语句后面的Promise状态变成reject,整个async函数会中断执行
如何解决async函数里面抛出错误,影响后续执行
async function asy() { try{ let a = await readfile('data/1.txt'); let b = await readfile('data/2.txt'); let c = await readfile('data/3.txt'); console.log(a.toString(), b.toString(), c.toString()); }catch(e){} } asy();
相关推荐
89500297 2020-06-07
陈旭阳 2020-06-02
前端开发Kingcean 2020-05-29
Magicsoftware 2020-03-28
Bonrui编程路 2020-06-07
niehanmin 2020-05-19
Magicsoftware 2020-03-28
LorenLiu 2020-03-28
lyg0 2020-02-18
88520191 2020-01-30
前端开发Kingcean 2020-01-23
csuzxm000 2020-01-10
whynotgonow 2020-01-05
89500297 2020-01-03
88520191 2019-12-30
Trustport 2019-12-16
wujiajax 2014-01-13