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

使函数调用同步

使函数调用同步

慕桂英4014372 2022-12-22 15:49:56
function first(){    console.log("1")}function second(){     new Promise ((resolve,reject)=>{        setTimeout(function(){            console.log("2")            resolve();        } ,0);     })  }function third(){    console.log("3")} async function run(){       first();    await second();    third();}run();需要使函数调用同步以获得最终输出 1,2,3 我尝试创建 promise 并使用 async await 但这对任何其他方式都没有帮助
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

将 setTimeout 打包成一个 promise 并在 setTimeout 中解析,


对该承诺使用 async await 以使其连续运行


function first() {

  console.log("1")

}


function second() {

  return new Promise(res => {

    setTimeout(function() {

      console.log("2");

      res()

    }, 0)

  })


}


function third() {

  console.log("3")

}


async function run() {


  first();

  await second()

  third();

}


run();


查看完整回答
反对 回复 2022-12-22
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

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