2015-01-07 3 views
1

У меня есть что-то похожее на следующее, и вы хотите знать, существует ли «цепной» способ сделать это, или если я не знаком, и это представляет собой запах. Благодаря!Цепочки, возвращающие массивы обещаний

var promises = Q.all(returns_a_promise()).then(returns_array_of_promises); 
    var more_promises = Q.all(promises).then(returns_another_array_of_promises); 
    var even_more_promises = Q.all(more_promises).then(yet_another_array_o_promises); 

    Q.all(even_more_promises).then(function() { 
    logger.info("yea we done"); 
    }); 

В идеале что-то вроде:

Q.all(returns_a_promise()) 
    .then(returns_array_of_promises) 
    .all(returns_another_array_of_promises) 
    .all(yet_another_array_o_promises) 
    .all(function() { 
    logger.info("yea we done"); 
    }); 

ответ

2
Q.all(returns_a_promise()) 
    .then(returns_array_of_promises).all() 
    .then(returns_another_array_of_promises).all() 
    .then(yet_another_array_o_promises).all() 
    .then(function() { 
    logger.info("yea we done"); 
    }); 
6

Просто вернуться Q.all из функций непосредственно, как этот

Q.all(returns_a_promise()) 
    .then(function() { 
     return Q.all(array_of_promises); 
    }) 
    .then(function() { 
     return Q.all(array_of_promises); 
    }) 
    .then(function() { 
     return Q.all(array_of_promises); 
    }) 
    .done(function() { 
     logger.info("yea we done"); 
    }); 

Например,

Q.all([Q(1), Q(2)]) 
    .spread(function(value1, value2) { 
     return Q.all([Q(value1 * 10), Q(value2 * 10)]); 
    }) 
    .spread(function(value1, value2) { 
     return Q.all([Q(value1 * 100), Q(value2 * 100)]); 
    }) 
    .spread(function(value1, value2) { 
     return Q.all([Q(value1 * 1000), Q(value2 * 1000)]); 
    }) 
    .done(function() { 
     console.log(arguments[0]); 
    }) 

напечатает

[ 1000000, 2000000 ] 
0

В зависимости от того, как ваши обещания структурированы, вы можете также использовать reduce упростить вещи:

var promiseGenerators = [ 
    returns_array_of_promises, 
    returns_another_array_of_promises, 
    yet_another_array_o_promises 
] 

promiseGenerators.reduce(function (chain, item) { 
    return chain.then(function() { 
    // invoke item, which returns the promise array 
    return Q.all(item()) 
    }); 
}, returns_a_promise()) 
.done(function() { 
    logger.info("yea we done"); 
})