promise generator async的用法

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();
  1. await 只能放在async函数里面
  2. 相比generator async语义化更强
  3. async返回一个promise
  4. await语句后面的Promise状态变成reject 那么async函数会中断执行
  5. try catch (await 异步语句)防止错误
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值