promise
const fs = require("fs");
function readFile(filename){
return new Promise((resolve,reject)=>{
fs.readfile(filename,(err,data)=>{
if(err) reject(err);
resolve(data);
});
});
}
//////////////////////////////////////////////readFile封装
readFile('data/a.txt').then(res=>{
console.log(res.toString);
return readFile(“data/b.txt");
}).then(res=>{
console.log(res.toString);
return readFile(“data/c.txt");
}).then(res=>{
console.log(res.toString);
})
generator
function *gen(){
yield readFile("data/a.txt");
yield readFile("data/b.txt");
yield readFile("data/c.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());
})
async
async function fn(){
let f1 = await readFile("data/a.txt");
console.log(f1.toString());
let f2 = await readFile("data/b.txt");
console.log(f2.toString());
let f3 = await readFile("data/c.txt");
console.log(f3.toString());
}
fn();
//////////////////////////////////////////////promise.all()
async function fn(){
let [f1,f2,f3] =await promise.all([
readFile("data/a.txt");
readFile("data/b.txt");
readFile("data/c.txt");
])
console.log(f1.toString());
console.log(f2.toString());
console.log(f3.toString());
}
fn();
- await 只能放在async函数里面
- 相比generator async语义化更强
- async返回一个promise
- await语句后面的Promise状态变成reject 那么async函数会中断执行
- try catch (await 异步语句)防止错误