等待不等待

时间:2019-05-02 20:47:55

标签: javascript

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;

为什么会看到以下情况?

  1. 输入f1。停止等待。
  2. 从f1返回(console.log(x)命令未执行)
  3. 将3分配给x(错误!已跳过,js向前移动)
  4. 在“ console.log(x)”行中返回f1。打印x。

为什么JS不等待等待并向前走?能给我个建议吗?

2 个答案:

答案 0 :(得分:2)

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();

答案 1 :(得分:1)

更简单

(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);
})();