javascript - 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());
})();
解决方案
在第一个代码块中,两个 Promise 都会立即初始化(当声明one
and时two
- 你有one = new Promise
and two = new Promise
),所以它们同时解析。
在第二个代码块中,只有在调用函数时才会创建 Promises。因为await
本质上会阻塞异步函数,在
console.log(await one());
console.log(await two());
在 中await one()
,您正在调用one
、创建一个 Promise,并等待它解决。
然后,在 Promise 解析并记录其值之后,console.log(await two())
调用第二个函数,创建 Promise,几秒钟后解析。
推荐阅读
- flutter - 在发送请求之前显示所有驱动程序
- node.js - 玩笑测试期间猫鼬内存泄漏 - 如何正确断开猫鼬?
- python - 当我从 python 代码创建对象时,Odoo 15 我的 onchange 函数没有被触发
- python - 如何在不每次遍历整个数据帧的情况下按天切片非常大的数据帧?
- mysql - AWS RDS 上 MySQL 的部分或轻量级副本
- highcharts - HighCharts 禁用 y 轴标签表示法
- swift - Swift 无法打开 CoreML 模型
- python - GAN结果图像在训练过程中是一样的
- video - 如何将视频从一台远程 PC 流式传输到另一台?(就像它在 Discord 中一样)
- node.js - 如何让用户在nodejs中使用用户名或电子邮件登录?