从快捷方式异步更改诺言

我有在示例中找到的这段代码,所有内容都在快捷方式中:


async function test1(){

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

    console.log('Completed test1');

    return p;

}

我想删除setTimeout而不是将其设置为非快捷方式,因此我可以向其中添加多个命令并执行其他操作,除了超时...


例如:


async function test1(){

    const p = await new Promise(resolve => setTimeout(resolve) => {

    // line here

    // another one etc

}

如何更改上面的代码?


慕哥6287543
浏览 119回答 1
1回答

GCT1015

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))用于创建一个承诺,该承诺将在2000毫秒后解决。您可以将其视为API调用,它将在2000毫秒后调用回调让我们打破这段代码:// A function test1 which is defined async sow you can use await inside itasync 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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript