鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ async函數(shù)塊之間如何同步執(zhí)行?

async函數(shù)塊之間如何同步執(zhí)行?

請問多個(gè)async函數(shù)塊之間如何同步的進(jìn)行執(zhí)行?
例子:以下兩個(gè)async函數(shù)塊如何順序進(jìn)行?

class Example {
    first;
    second;
    constructor(){
    }
    
    async  getFirstVal(){
     this.first = await [一個(gè)promise]
    }
    
    async  getSecondVal(){
    this.second = await[一個(gè)依賴于first的promise]
    }
    
    async  getOtherVal(){
    this.other = await[一個(gè)promise]
    }
    
    doSomeWork(){
    this.getFirstVal(); 
    this.getSecondVal();
    this.getOtherVal();
    ........
    }
}

請問,怎么做才能保證doSomeWork里面的firstsecond這兩個(gè)異步塊順序執(zhí)行?
我不想將second這一部分的邏輯寫入getFirstVal方法中,雖然這樣能獲得正確的執(zhí)行順序,因?yàn)間etFirstVal可能在很多地方都會(huì)異步調(diào)用到,我想將他封裝成一個(gè)單獨(dú)的函數(shù)。請問有什么好的方法幫助我實(shí)現(xiàn)這種async塊之間的順序執(zhí)行嗎?

回答
編輯回答
何蘇葉
    function async2() {
        console.log( 'async2');
    }
    async function async1(resolve) {
        await setTimeout(function () {
            console.log("settimeout");
            //當(dāng)我認(rèn)定async1完成后才開始async2
            resolve()
        },0);
    }
    new Promise(function (resolve) {
        async1(resolve)
    }).then(function () {
        async2()
    });
或者
new Promise(function (resolve) {
        async1()
        resolve()
    }).then(function () {
        async2()
    });
2018年6月10日 17:03
編輯回答
挽歌
async doSomeWork() {
    await  this.getFirstVal(); 
    this.getSecondVal();
    this.getOtherVal();
}

這樣可以嗎?優(yōu)雅的方案也沒太研究過,但是你可以 看看 Rxjs 或者 async 這些庫,能得到比較好的思路

2018年1月28日 02:33