为什么承诺链不能按预期工作(链接任务)

Why the promises chains does not work as expected (chaining tasks)

如果链条没有像预期的那样工作,那么使用带有“.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

第二个 then 必须 return 另一个承诺,如果你想让 third then 在超时后触发第二个然后.

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

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,即 undefined.

我看起来像你期望你从第二次超时的回调中 returning 得到的结果以某种方式作为第二次 then 的结果传递,但那是不是它的工作方式。