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();