Javascript Promise resolve 方法打印在控制台中。如何?

Javascript Promise resolve method prints in console. How?

请查看下面的 javascript 代码。当我 运行 浏览器控制台中的这段代码 window 收到下面提到的输出。我是 javascript 的新手,我保证。请帮助我了解如何在浏览器控制台中打印“已解决”?


<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre><code>    function resolveAfter2Seconds() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('resolved');
        }, 2000);
      });
    }
     
    async function asyncCall() {
      console.log('calling');
      const result = await resolveAfter2Seconds();
      console.log(result);
    }
    asyncCall();

浏览器控制台中的输出:

打电话

已解决

现在我的问题是为什么“已解决”会打印在控制台中?据我所知, then() 方法应该在调用 resolve() 方法时执行。

await运算符用于等待Promise结算。它 returns Promise 的已实现值或如果它不是 Promise 的值本身。

在你的代码中,由于resolveAfter2Seconds()函数returns一个Promise,所以在下面的语句中

const result = await resolveAfter2Seconds();

javascript 等待 Promise 稳定下来,然后将其完成值赋值,即 'resolved'result 常量。之后,您在控制台上记录 result,这就是 'resolved' 在控制台上记录的原因。

asyncCall 函数中每个语句上方的注释将帮助您理解输出。

async function asyncCall() {
  // log 'calling' on the console
  console.log('calling');   

  // wait for the promise to resolve and then
  // assign the fulfillment value to 'result'                   
  const result = await resolveAfter2Seconds(); 

  // log the value with which promise returned
  // by 'resolveAfter2Seconds' function resolved
  console.log(result);                         
}

As of what I know is then() method should have executed when resolve() method is called.

我看不到您在代码中的什么地方调用了 .then() 方法。如果您在任何 Promise.

上注册任何回调调用 .then() 方法,则会调用 .then() 方法

您可以如下所示更改代码,而不是使用 async-await 语法,以查看在 2 秒后调用使用 .then() 注册的回调。

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

// store the promise returned by 'resolveAfter2Seconds' function
const p = resolveAfter2Seconds();

// register a callback function to be invoked after 2
// seconds with the resolved value
p.then(resolvedValue => {
  console.log('callback invoked');
  console.log('Promise resolved with the value of: ' + resolvedValue);
}).catch(error => console.log(error));

从您的问题中可以清楚地看出您对代码的输出感到困惑,因为它使用 async-await 语法而不是 promise-chainingasync-await 是使用 .then() 方法调用的常规承诺代码的语法糖。

我建议您访问以下链接以了解 async-await 语法的工作原理。一旦你理解了这一点,你就能够理解输出。