首页 > 解决方案 > Cannot understand behaviour of promises in javascript

问题描述

Code block 1 executes in 2 seconds.

Code block 2 executes in 4 seconds.

Can someone explain what is the difference between them ?

// Code block 1

const one = new Promise(resolve => setTimeout(() => resolve('one'), 2000));
const two = new Promise(resolve => setTimeout(() => resolve('two'), 2000));

(async() => {
  console.log(await one);
  console.log(await two);
})();

// Code block 2

const one = () => new Promise(resolve => setTimeout(() => resolve('one'), 2000));
const two = () => new Promise(resolve => setTimeout(() => resolve('two'), 2000));

(async() => {
  console.log(await one());
  console.log(await two());
})();

标签: javascriptpromise

解决方案


在第一个代码块中,两个 Promise 都会立即初始化(当声明oneand时two- 你有one = new Promiseand two = new Promise),所以它们同时解析。

在第二个代码块中,只有在调用函数时才会创建 Promises。因为await本质上会阻塞异步函数,在

console.log(await one());
console.log(await two());

在 中await one(),您正在调用one、创建一个 Promise,并等待它解决。

然后,在 Promise 解析并记录其值之后,console.log(await two())调用第二个函数,创建 Promise,几秒钟后解析。


推荐阅读