2016-12-19 1 views
1

나는 병렬 배열을 실행하고 완료되면 순서대로 반환하기 위해 Bluebird (또는 필요한 경우 기본 약속)에서 효율적인 방법을 찾고 있습니다. 대기열 잠금 장치와 거의 같습니다.병렬 약속 반환 순서

그래서 5 개의 함수가 배열 된 경우 함수 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 coroutines로 이것을 수행 할 수 있다고 생각합니까? 가장 감각적 인 구조를 결정하는 데 어려움을 겪는 것은 위의 예와 가장 비슷합니다. 방금 모든 약속을 기다리는 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!') 
}); 

하나가 완료 할 때 필요한 경우 수 .tapthem through .MAP before passing them to .all` (반환 값이 변경되지 않는 then) : 경우에 지정하는 순서대로 실행됩니다 그래서 .tap(),

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

음을? 따라서 fn5()가 먼저 완료되면 fn1-4가 완료되어서 내 시퀀스가 ​​유지 될 때까지 기다릴 것입니까? 만약 그렇다면 ... 멋지다. 쉬운 일이다 .-p – ddibiase

+0

'tap'하지 않을 것이다. 만약 당신이 그것의 시퀀스를 원한다면'.ttap's를'.map' 대신'.each' 할 수 있습니다. 'Promise.each ([fn1(), ....], x => x.tap (...))'(블루 버드 또는 다른 약속 라이브러리의'.reduce') –

+0

그건 정말 내가 원하는 결과를 그물에 쏟아 붓는거야? – ddibiase