2014-06-17 20 views
6

Ho diverse promesse (P1, P2, ... Pn) Vorrei raggrupparle in sequenza (quindi Q.all non è un'opzione) e vorrei piace rompere la catena al primo errore.
Ogni promessa viene fornita con i propri parametri.
E mi piacerebbe intercettare ogni errore di promessa per scaricare l'errore.Interrompere una sequenza dinamica di promesse con Q

Se P1, P2, .. PN sono le mie promesse, non ho idea di come automatizzare la sequenza.

risposta

3

Se hai una serie di promesse, sono già state avviate e non c'è nulla che tu possa fare per avviarne o fermarne una (puoi annullare, ma è fin dove arriva).

Supponendo di avere F1,... Fnfunzioni promessa di tornare, è possibile utilizzare il blocco di base costruzione di promesse, la nostra .then per questo:

var promises = /* where you get them, assuming array */; 
// reduce the promise function into a single chain 
var result = promises.reduce(function(accum, cur){ 
    return accum.then(cur); // pass the next function as the `.then` handler, 
        // it will accept as its parameter the last one's return value 
}, Q()); // use an empty resolved promise for an initial value 

result.then(function(res){ 
    // all of the promises fulfilled, res contains the aggregated return value 
}).catch(function(err){ 
    // one of the promises failed, 
    //this will be called with err being the _first_ error like you requested 
}); 

Quindi, la versione meno annotata:

var res = promises.reduce(function(accum,cur){ return accum.then(cur); },Q()); 

res.then(function(res){ 
    // handle success 
}).catch(function(err){ 
    // handle failure 
}); 
+0

Grazie ! Tuttavia, suppongo che il "risultato aggregato" passato come argomento nell'ultimo "allora" sia qualcosa che devo implementare io stesso secondo la mia convenienza? – Guid

+1

@Guid Dipende dalla tua API, ho assunto che ogni promessa richieda il risultato della precedente (dato che le hai richieste in sequenza). Ad esempio, potresti creare un array all'esterno e "spingere" ad esso nel ciclo (prima della parte "return accum.then (cur);'), e poi ".return" i risultati. –

Problemi correlati