:約束(request
の約束を返すバージョンが必要)で
const makeRequest = (item, cb) => request({
uri: 'http://some.url/',
method: 'POST',
data: item
}, cb);
// 1. reverse() so that we can start building the callback chain from the end
// 2. Build up callback chain (starting with no-op function passed in as initial state
// to reduce) by returning a function which calls makeRequest() with the current item
// and passes the existing chain of callbacks to be called after that request finishes
const callbackChain = array.reverse().reduce((chain, item) => {
return() => makeRequest(item, chain);
},() => {});
callbackChain();
:
let promise = Promise.resolve();
// You can always attach more .then callbacks to an existing promise
for (let item of array) {
promise = promise.then(() => request({
uri: 'http://some.url/',
method: 'POST',
data: item
}));
}
またはArray#reduce
と:
const promise = array.reduce((promise, item) => {
return promise.then(() => request({
uri: 'http://some.url/',
method: 'POST',
data: item
}));
}, Promise.resolve());
1つのオプション:約束。ここでヘルパーメソッドです:https://www.npmjs.com/package/promise-reduce – undefined
しかし、それらをチェーンする方法は? @Ram – F1ks3r
このブルーバードのドキュメントページにはいくつかの例があります:http://bluebirdjs.com/docs/api/promise.reduce.html還元機能は約束を返すべきであり、リクエストを順番に実行すべきでない場合は、 'Promise.each'ヘルパー。 – undefined