2016-02-05 72 views
0

我想創建一個從服務器獲取數據的請求鏈,但是在每個請求之間應該發生延遲X秒。爲延遲請求處理創建一個承諾鏈

應該是這樣的:

const data = {}; 
const promises = Promise.resolve(); 
for (let elem of longArray) { 
    promises.then(() => { 
     return sendRequest(); // returns promise 
    }) 
    .then((response) => { 
     // Store response stuff in data 
    }) 
    .then(() => { 
     // Wait here for X seconds before continuing 
    }) 
} 

promises.finally(() => { 
    // Log stuff from data 
}); 

不過,我不明白這一點做我想要的。它立即啓動所有請求,然後進入響應處理程序。數據填充之前調用finally部分。

+0

的我不知道你想要的行爲但是,你有沒有試過[Promise.all](http://bluebirdjs.com/docs/api/promise.all.html)? –

+0

是的,我有。使用Promise.all立即運行我在數組中收集的所有承諾 - 無需延遲。 – akohout

回答

2

當您使用藍鳥,它使用array.reduce

const data = {}; 
longArray.reduce((promise, item) => 
    promise 
     .then(() => sendRequest()) 
     .then(response => { 
      // Store response stuff in data 
     }).delay(X), Promise.resolve()) 
.finally(() => { 
    // Log stuff from data 
}); 

或很簡單 - 用你的......循環

const data = {}; 
const promises = Promise.resolve(); 
for (let elem of longArray) { 
    promises = promises 
    .then(() => sendRequest()) 
    .then(response => { 
     // Store response stuff in data 
    }) 
    .delay(X); 
} 

promises.finally(() => { 
    // Log stuff from data 
}); 
+0

非常感謝,它的工作原理! (只試過第二個版本) – akohout

+0

無論如何它們在功能上是相同的:p –