第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從快捷方式異步更改諾言

從快捷方式異步更改諾言

慕哥6287543 2021-05-02 14:15:37
我有在示例中找到的這段代碼,所有內容都在快捷方式中:async function test1(){    const p = await new Promise(resolve => setTimeout(resolve, 2000)).then(()=>'test1');    console.log('Completed test1');    return p;}我想刪除setTimeout而不是將其設置為非快捷方式,因此我可以向其中添加多個命令并執(zhí)行其他操作,除了超時...例如:async function test1(){    const p = await new Promise(resolve => setTimeout(resolve) => {    // line here    // another one etc}如何更改上面的代碼?
查看完整描述

1 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

async function test1(){

    const p = await new Promise(resolve => setTimeout(resolve, 2000)).then(()=>'test1');

    console.log('Completed test1');

    return p;

}

我認為您尚未完全理解此代碼。setTimeout不是捷徑。new Promise(resolve => setTimeout(resolve, 2000))用于創(chuàng)建一個承諾,該承諾將在2000毫秒后解決。您可以將其視為API調用,它將在2000毫秒后調用回調


讓我們打破這段代碼:


// A function test1 which is defined async sow you can use await inside it

async function test1(){

    // You can await for promises.

    //  As explained await new Promise(resolve => setTimeout(resolve, 2000)) 

    // is just a promise resolving after 2000ms

    const p = await new Promise(resolve => setTimeout(resolve, 2000))

     // .then block will run after promise gets resolved

     // p will bcome test1

    .then(()=>'test1');

    console.log('Completed test1');

    return p;

}

如果您想有條件地解決Promise并進行一些計算,則可以在setTimeout函數中進行以下操作:


await new Promise(resolve => 

    setTimeout(()=>{

        if('Some consition'){

            resolve('some value')

        }

        else{

            resolve('some other value')

        }

    }, 2000)

)


查看完整回答
反對 回復 2021-05-13
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號