JS异步

同步sychronous:任务的执行时一个接着一个执行的,上一个任务执行完成才能继续下一个任务

异步asychronous:是js这种单线程语言解决多任务的一种方法:将耗时的任务(io)设定为异步任务,先将诶浏览器负责相关功能的线程来实现耗时部分工作,而主线程继续下面的任务,不阻塞代码,后续通过通知的方式来实现异步任务的其他代码执行

//ES7异步有序实现
async function es7() {
let food = await new Promise((resolve) => {
console.log("买菜开始了");
setTimeout(() => {
let a = "茄子,罗布,大白菜"
console.log("菜完成了");
resolve(a);
}, 1000);
});
let foodD = await new Promise((resolve) => {
console.log(`我准备把${food}全部洗干净并且切好`);
setTimeout(() => {
let b = "鱼香茄子材料";
console.log(`我已经把${food}全部洗干净并且切好`);
resolve(b);
}, 1000);
});
let eatFood = await new Promise((resolve) => {
console.log(`我开始使用${foodD}炒菜了`);
setTimeout(() => {
console.log(`鱼香茄子完成了`);
resolve("一盘美味的鱼香茄子");
}, 1000);
});
return eatFood;
}
let res = es7();
 
//利用生成器函数配合promise实现异步有序
function* foo() {
yield new Promise((resolve) => {
console.log("a任务开始了");
setTimeout(() => {
console.log("a任务完成了");
resolve();
}, 1000);
});
yield new Promise((resolve) => {
console.log("b任务开始了");
setTimeout(() => {
console.log("b任务完成了");
resolve();
}, 1000);
});
yield new Promise((resolve) => {
console.log("c任务开始了");
setTimeout(() => {
console.log("c任务完成了");
resolve();
}, 1000);
});
}

let gen = foo();

gen.next().value.then(() => {
return gen.next().value;
}).then(() => {
return gen.next().value;
})

相关推荐