我寫了這個庫,也許它可以幫助你 https://github.com/LvChengbin/sequence
你可以從NPM安裝:
npm i @lvchengbin/sequence --save
然後你可以像這樣實施:
Sequence.all([
() => promise1,
() => promise2,
() => promise3
]).then(results => {
// here you will get all results of the promises in the list
}).catch(results => {
// any of promises failed, and you can get all results of them
});
如果要執行列表中的所有步驟,不管其中是否成功或失敗,你可以使用Sequence.chain
Sequence.all([
() => promise1,
() => promise2,
() => promise3
]).then(results => {
// here you will get all results of the promises in the list, and you can know which one has succeeded and which one has failed with
if(results[ 0 ].status === Sequence.SUCCEEDED) {
console.log(results[ 0 ].value);
}
})
您還可以創建一個空序列,後來追加的步驟。
const sequence = new Sequence();
sequence.append(promise1);
sequence.append([ promise1, promise2 ]);
sequence.on('success', (result, index, results) => {
// this function will execute for each item succeeded.
});
sequence.on('failed', (result, index, results) => {
// this function will execute for each item failed.
});
sequence.on('end',() => {
// this function will be executed after all steps in the sequence finished. but you can also append more steps later.
});
如果需要,可以執行這樣的每個步驟指定一個interval
:
Sequence.all([], 1000);
Sequence.chain([], 1000);
Sequence.any([], 1000);
new Sequence([], { interval : 1000 });
所有上面的代碼將執行序列中的各個步驟以1秒的時間間隔。
來源
2018-01-23 02:31:21
LCB
從我的其他答案和downvotes,似乎更多的人需要閱讀[rsvp自述](https://github.com/tildeio/rsvp.js?utm_source=javascriptweekly)它解釋「真的很棒一部分來自你從第一個處理程序返回一個承諾「。如果你不這樣做,你真的錯過了承諾的表達力量。 –
類似的問題,但不是框架特定的:http://stackoverflow.com/q/24586110/245966 –