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

等待不等待

等待不等待

qq_遁去的一_1 2021-05-05 13:21:52
function resolveAfter2Seconds(x) {    return new Promise(resolve => {        setTimeout(() => {            resolve(x);        }, 2000);    });}async function f1() {    var x = await resolveAfter2Seconds(10);    console.log(x); }f1();let x =  3;为什么会看到以下情况?输入f1。停止等待。从f1返回(console.log(x)命令未执行)为x分配3(错误!等待跳过,js向前执行)返回“ console.log(x)”行上的f1。打印x。为什么JS不等待等待并向前迈进?你能给我个建议吗?
查看完整描述

2 回答

?
呼如林

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

f1是异步的(等待仅在该异步上下文中发生)。因此,将执行f1(),并且由于它是异步的,因此该let x = 3;行无需等待即可立即执行。


如果您还await调用f1(),它应该可以完成您的期望。但是,为了使用await,您必须将该代码包装在另一个异步函数中,然后执行该函数。


演示(不等待):


function resolveAfter2Seconds(x) {

    return new Promise(resolve => {

        setTimeout(() => {

            resolve(x);

        }, 2000);

    });

}


async function f1() {

    var x = await resolveAfter2Seconds(10);

    console.log(x); 

}


f1();

let x =  3;

console.log(x);

工作版本(需要额外等待):


function resolveAfter2Seconds(x) {

  return new Promise(resolve => {

    setTimeout(() => {

      resolve(x);

    }, 2000);

  });

}


async function f1() {

  var x = await resolveAfter2Seconds(10);

  console.log(x);

}


async function f2() {

  await f1();

  let x = 3;

  console.log(x);

};


f2();


查看完整回答
反对 回复 2021-05-20
?
阿晨1998

TA贡献2037条经验 获得超6个赞

更简单


(async function() {


  function resolveAfter2Seconds(x) {

    return new Promise(resolve => {

      setTimeout(() => {

        resolve(x);

      }, 2000);

    });

  }


  async function f1() {

    var x = await resolveAfter2Seconds(10);

    console.log(x);

  }



  await f1();

  let x = 3; 

  console.log(x);

})();


查看完整回答
反对 回复 2021-05-20
  • 2 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

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