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,... Fn
funzioni 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
});
fonte
2014-06-17 11:09:19
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
@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. –