javascript - 对 Promise 感到困惑,为什么打印“1 2 11 22”而不是“1 2 22 11”?
问题描述
我对Javascript中的Promise不是很擅长,今天看到一个让我困惑了一会儿的问题,代码如下:
new Promise((res, rej) => {
res();
})
.then(() => {
console.log(1);
new Promise((res, rej) => {
res();
})
.then(() => {
console.log(2);
})
.then(() => {
console.log(22);
});
})
.then(() => {
console.log(11);
});
我认为结果应该是 1 2 22 11,但我错了,真正的答案是1 2 11 22
为什么?请帮帮我,谢谢!
解决方案
我们可以把它分成三部分:A、B、C
new Promise((res,rej)=>{
// Part A
res()
}).then(()=>{
// Part B
console.log(1)
new Promise((res,rej)=>{
// Part B-1
res()
}).then(()=>{
// Part B-2
console.log(2)
}).then(()=>{
// Part B-3
console.log(22)
})
}).then(()=>{
// Part C
console.log(11)
})
它从 print 1开始, 然后内部的 Promise 被解决(B-1 部分),两个任务被插入到任务队列中:
- B-2 部分
console.log(2)
- C部分
console.log(11)
然后执行第一个任务: print 2,完成后,在任务队列的末尾添加了另一个任务,新的任务队列如下所示:
- C部分
console.log(11)
- B-3部分
console.log(22)
然后按顺序执行任务:打印11和22
所以结果是1 2 11 22
顺便说一句,如果我们想要1 2 22 11的顺序,我们可以在内部 promise 前面 添加关键字return :
new Promise((res,rej)=>{
res()
}).then(()=>{
console.log(1)
return new Promise((res,rej)=>{
res()
}).then(()=>{
console.log(2)
}).then(()=>{
console.log(22)
})
}).then(()=>{
console.log(11)
})
结果是1 2 22 11
推荐阅读
- c# - Appium - 检查元素是否存在
- agora.io - Agora 是否支持 Safari 屏幕共享?
- devops - 从 Github 提取周期时间
- numpy - LSTM 训练误差非常高且相对不变
- openid-connect - 在 OIDC 中,授权码和授权令牌有什么区别?
- python - 为什么我在 python 上的全局声明之前得到“变量分配”
- datetime - 绘图仪只绘制时间,而不是日期
- django - social-auth-app-django 如何与 jinja2 一起工作?
- php - php 变量 - 将变量传递到另一个 php 页面的最佳方式
- python-3.x - tribonacci序列python代码在while循环中跳过for循环