使用promise来实现async

发布于:2021-07-18 17:39:04

async本质是什么? 其实就是generator的语法糖是自动执行的generator,虽然ES6已经实现了asyncgenerator,但是在生产环境中都是经过babel编译成promise.


简单的async

async function p1(){
console.log(1)
return 1
}
// 等效
function p1(){
console.log(1)
return Promise.resolve(1)
}
复制代码

一般情况的async

async function p2(){
console.log(2)
let a = await new Promise(resolve => setTimeout(() =>resolve(1), 3000) )
console.log(a);
return 2
};
// 等效
function p2(){
console.log(2)
return Promise.resolve(new Promise(resolve => setTimeout(() =>resolve(1), 3000)).then(res => {
let a = res;
console.log(a)
return Promise.resolve(2)
}))
}

复制代码

循环中的async

通过队列实现


let p1 = () => new Promise((resolve => setTimeout(() => resolve(1), 1000)));
let p2 = () => new Promise((resolve => setTimeout(() => resolve(2), 2000)));
let p3 = () => new Promise((resolve => setTimeout(() => resolve(3), 3000)));
let ps = [p1, p2, p3];
async function p(){
for (let i = 0; i < 3; i++) {
let a = await ps[i]();
console.log(a)
}
}
// 等效
async function p(){
let queue = [];
for (let i = 0; i < 3; i++) {
queue.push(() => ps[i]().then(res => {
let a = res;
console.log(a)
}))
}
queue.reduce((p1, p2) => p1.then(res => p2()) , Promise.resolve());
};
复制代码

可以看出来async简化了Promise,大部分场景下Promise其实也够用了,但是在链式调用的场景下使用async非常简洁. 下面抛出一个问题


let p1 = new Promise((resolve) => resolve(1))
let p2 = new Promise((resolve) => {
resolve(p1);
new Promise(resolve => resolve()).then(() => console.log(2));
})
p2.then(res => console.log(1))
// 为什么先执行2然后执行1?

resolve(p1)其实等效于 Promise.resolve().then(res => p1.then(resolve))
所以事件队列的进入顺序为
// res => p1.then(resolve)
// () => console.log(2)
// resolve
复制代码






相关资源:DirectX修复工具V4.0增强版

相关推荐

最新更新

猜你喜欢