为了账号安全,请及时绑定邮箱和手机立即绑定

从快捷方式异步更改诺言

从快捷方式异步更改诺言

慕哥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而不是将其设置为非快捷方式,因此我可以向其中添加多个命令并执行其他操作,除了超时...例如: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))用于创建一个承诺,该承诺将在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 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信