2015-05-20 28 views
0

我有很多的承諾(使用Q),我要依次調用,這裏是我的代碼:動態序列從來沒有去追趕

// All the promises are called sequentially 
      var result = promises.reduce(function(promise, item) { 
       return promise.then(function() { 
        var obj = toPush.shift(); 
       }); 
      }, Q()); 

      // Check the result 
      result.then(function() { 
       // Do something if all of the promises full 
      }).catch(function() { 
       // Do something if ONE of the promise is rejected and stop the others 
      }).finally(function() { 
       App.network.stopLoader(); 
      }); 

承諾是承諾的數組(回調功能)

它工作的很棒,所有的承諾都是按順序完成的,但是當一個承諾被拒絕時,它仍然會在then函數中而不是catch中。 爲什麼?

我已經使用這個:Break a dynamic sequence of promises with Q

感謝您的幫助:)

+0

什麼是'promises',什麼是'toPush'?你爲什麼要改變它,你在用'obj'做什麼?它看起來不像你的順序代碼是完全異步的。 – Bergi

+0

promises是一個包含返回promise的函數的數組的tab,toPush是一個允許我構造tab選項的tab,如果promise已經解決,然後toPush.shift,否則我需要停止所有其他promise並保存toPush。 –

+0

'promises'數組中的那些函數從未真正被調用 - 您不使用'item'!我想知道你爲什麼認爲他們被罰款。 – Bergi

回答

0

原因美中不足的是從來沒有所謂的,因爲歐沒有在這部分代碼返回任何東西:

return promise.then(function() { 
    var obj = toPush.shift(); 
}); 

相反,你應該嘗試:

return promise.then(function() { 
    return toPush.shift(); 
}); 

如果你這樣做:

result.then(console.log) 

你應該總是看到未定義,不會被抓住。

希望這會有所幫助!

+0

感謝您的回答,但它不起作用。但我應該回報一些東西,你說得對。 –

0

看起來你只是想Q.all:

Q.all(promises).then(function() { 
    // Do something if all of the promises full 
}).catch(function() { 
    // Do something if ONE of the promise is rejected and stop the others 
}).finally(function() { 
    App.network.stopLoader(); 
}); 

按照documentation,所有返回的承諾將盡快陣列中任何的承諾是遭到拒絕。 (與所有已解決的等待所有承諾在解決退還的承諾前解決的問題相反)。