首页 > 解决方案 > Javascript Promise resolve 方法在控制台中打印。如何?

问题描述

请看下面的 javascript 代码。当我在浏览器控制台窗口中运行此代码时,会收到下面提到的输出。我是 javascript 和承诺的新手。请帮助我了解如何在浏览器控制台中打印“已解决”?


    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() 方法时执行。

标签: promisees6-promise

解决方案


await运算符用于等待Promise结算。Promise如果它不是 a ,它会返回 the 或值本身的已实现值Promise

在您的代码中,由于resolveAfter2Seconds()函数返回 a 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);                         
}

据我所知, then() 方法应该在调用 resolve() 方法时执行。

我看不到您.then()在代码中调用方法的位置。.then()如果您在 any 上注册任何回调调用.then()方法,则会调用方法Promise

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

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-chaining. async-await是使用.then()方法调用的常规承诺代码的语法糖。

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


推荐阅读