gpt4 book ai didi

javascript - 为什么 promise 链不能按预期工作(链接任务)

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:46 26 4
gpt4 key购买 nike

如果它没有像预期的那样工作,那么使用带有 '.then' 的链有什么优势:

new Promise(function(resolve, reject) { 
// A mock async action using setTimeout
setTimeout(function() { resolve(10); }, 3000);
})

.then(function(num) {
console.log('first then: ', num); return num * 2; })

.then(function(num) {
setTimeout(function() {
console.log('second then: ', num); return num * 2; }, 500);
})

.then(function(num) {
console.log('last then: ', num);
});

// RESULT!
// From the console:
// first then: 10
// last then: undefined
// second then: 20

我期待以下结果:

// RESULT!
// From the console:
// first then: 10
// second then: 20
// last then: 40

最佳答案

如果您希望 third then 在第二个 then 超时后触发,则第二个 then 必须返回另一个 promise 。 p>

此版本的代码将为您提供所需的结果:

new Promise(function (resolve) { 
setTimeout(function() {
resolve(10);
}, 3000);
})
.then(function (num) {
console.log('first then: ', num); return num * 2;
})
.then(function (num) {
return new Promise(function (resolve) {
setTimeout(function () {
console.log('second then: ', num);
resolve(num * 2);
}, 500);
});
})
.then(function (num) {
console.log('last then: ', num);
});

您的代码未按预期工作的原因是在第二次超时开始后立即调用了第三个 then,调用 setTimeout 的结果,这是未定义

我看起来像您期望您从第二次超时的回调返回的结果以某种方式作为第二次 then 的结果传递,但这不是它的工作方式。

关于javascript - 为什么 promise 链不能按预期工作(链接任务),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46990153/

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