2016-12-19 5 views
1

私は、約束事の並行した配列を実行し、完了した順にそれらを返すために、Bluebird(または必要ならばPromise)を効率的に探しています。キューロックのようなものだと思いますか?並行して約束を返す

したがって、関数1には150ms、関数2には50ms、関数3には50msなどがあります。5つの関数はすべて並列に呼び出されますが、値を返すコールバックは私が指定する注文。理想的には次のようなものです:

Promise.parallelLock([ 
    fn1(), 
    fn2(), 
    fn3(), 
    fn4(), 
    fn5() 
]) 
.on('ready', (index, result) => { 
    console.log(index, result); 
}) 
.then(() => { 
    console.log('Processed all'); 
}) 
.catch(() => { 
    console.warn('Oops error!') 
}); 

私はBluebirdコルーチンを使ってこれを達成できると思いますか?最も理にかなった構造を決めるのが難しい/上記の例と最もよく似ています。ただ単に、すべての約束を待ちPromise.all

答えて

3

、約束は値のようなものです - あなたはアクションがすでに実行された約束を持っている場合:

Promise.all([ 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1() 
]) 
.then(results => { 
    // this is an array of values, can process them in-order here 
    console.log('Processed all'); 
}) 
.catch(() => { 
    console.warn('Oops error!') 
}); 

使用すると、1つが行われたときに知っておく必要がある場合は、することができます.tap(戻り値を変更しないthenthem through .MAP before passing them to .all`:

Promise.all([ 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1(), 
    fn1() 
].map((x, i) => x.tap(v => console.log("Processed", v, i)) 
.then(results => { 
    // this is an array of values, can process them in-order here 
    console.log('Processed all'); 
}) 
.catch(() => { 
    console.warn('Oops error!') 
}); 
+0

うーん、そう.TAP()は、私だけが指定された順序で実行されますか?したがって、最初にfn5()が終了すると、fn1-4が完了してシーケンスが維持されるまで待機しますか?もしそうなら...いいです、それは簡単でした:-p – ddibiase

+0

'tap'はそうではありません、あなたが'。 'Promise.each([fn1()、....]、x => x.tap(...))'(ブルーバード、または他の約束ライブラリの '.reduce') –

+0

ネット私は私が望んでいる結果ですか? – ddibiase