gpt4 book ai didi

javascript - 如何预测 Promises 的异步性质

转载 作者:行者123 更新时间:2023-11-29 14:43:44 25 4
gpt4 key购买 nike

我有一段代码示例,我无法预测代码的流程。

var x = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([1, 2, 3]);
}, 0);
});
};

x().then((val) => {
console.log(val);
}).catch((err) => {
console.log(err.message);
});

console.log("hello");

for (var i = 0; i < 10; i++) {
console.log(i);
}

var y = Promise.all([Promise.resolve(1), Promise.reject(Error("err"))]);

y.then((arr) => {
console.log(arr);
})
.catch((err) => {
console.log(err);
});

Promise.resolve('ta-da!')
.then((result) => {
console.log('Step 2 received ' + result);
return 'Greetings from step 2';
})
.then((result) => {
console.log('Step 3 received ' + result);
})
.then((result) => {
console.log('Step 4 received ' + result);
return Promise.resolve('fulfilled value');
})
.then((result) => {
console.log('Step 5 received ' + result);
return Promise.resolve();
})
.then((result) => {
console.log('Step 6 received ' + result);
});

日志按以下顺序排列:

"hello"
0
1
2
3
4
5
6
7
8
9
"Step 2 received ta-da!"
"Step 3 received Greetings from step 2"
"err"
"Step 4 received undefined"
"Step 5 received fulfilled value"
"Step 6 received undefined"
[1, 2, 3]

for 循环正在按预期执行。setTimeout() 按预期工作, promise 在事件循环后实现。

其他 2 个 promise 发生冲突。我期待 promise 会立即同步实现,结果会是

"hello"
0
1
2
3
4
5
6
7
8
9
"err"
"Step 2 received ta-da!"
"Step 3 received Greetings from step 2"
"Step 4 received undefined"
"Step 5 received fulfilled value"
"Step 6 received undefined"
[1, 2, 3].

即使 promise 是异步解决的。它们是如何发生冲突的。

附上截图。

enter image description here

最佳答案

您的代码中有三个独立的 promise 链:

  1. x()开头的,因为超时需要最长的
  2. y开头的那个(来自Promise.all(…))抛出错误的地方
  3. Promise.resolve('ta-da!') 开头的那个

他们不会互相等待 - 你没有告诉他们去做,他们也不会神奇地自己去做。
相反,它们的流程是任意交错的,就像标准异步函数的情况一样(想想两个具有不同周期的 setInterval)。

I was expecting the promises will be fulfulled immediately in syncronously

没有。 Promise 回调总是(可靠地)是异步的,即使 promise 已经确定。

关于javascript - 如何预测 Promises 的异步性质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com