下面的代码来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

我不明白resolveAfter2Seconds(20)如何为变量a返回20

我认为,从resolved Promise获取“返回值”的唯一方法是使用Promise.prototype.then()。下面的代码不使用then(),但仍可以获取20。为什么?我错过了什么还是误会了什么?

  function resolveAfter2Seconds(x) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(x);
        }, 2000);
      });
    }

async function add1(x) {
  var a = resolveAfter2Seconds(20);
  var b = resolveAfter2Seconds(30);
  return x + await a + await b;
}

add1(10).then(v => {
  console.log(v);  // prints 60 after 2 seconds.
});

async function add2(x) {
  var a = await resolveAfter2Seconds(20);
  var b = await resolveAfter2Seconds(30);
  return x + a + b;
}

add2(10).then(v => {
  console.log(v);  // prints 60 after 4 seconds.
});

最佳答案

等待返回解析值

但是但是

不返回拒绝值

为此,我们需要使用try-catch块。您可以参考示例:

function resolveAfter2Seconds(x) {
 return new Promise(reject => {
  setTimeout(() => {
   reject(x);
  }, 2000);
 });
}

async function add1(x) {

 try {
  return await resolveAfter2Seconds(20);
 } catch (e) {
  return e
 }

}

add1(10).then(v => {
 console.log(v);
});

09-25 18:11