簡體   English   中英

為什么承諾鏈不能按預期工作(鏈接任務)

[英]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

第二個有,如果你想在第三個則在第二超時然后火后返回另一個承諾。

此版本的代碼將為您提供所需的結果:

 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); }); 

為什么預期你的代碼沒有工作的原因是第三然后立即調用第二超時啟動后,與調用的結果setTimeout ,這是不確定的

我看起來像你期望你是從第二超時回調返回結果作為第二結果以某種方式通過的 ,但這不是它的工作方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM