使用promise來實現async

async本質是什麼? 其實就是generator的語法糖是自動執行的generator,雖然ES6已經實現了asyncgenerator,可是在生產環境中都是通過babel編譯成promise.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

經過隊列實現bash

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很是簡潔. 下面拋出一個問題babel

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
複製代碼
相關文章
相關標籤/搜索