2016-02-05 85 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 –