[英]Chaining functions that return arrays of promises
我有類似以下內容的內容,並且想知道是否有“鏈式”方式來執行此操作,或者我是否記錯了,這表示有異味。 謝謝!
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");
});
像這樣直接從函數中返回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 ]
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");
});
根據您的諾言的結構,您還可以使用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");
})
以下是等效的:
return Q.all([a, b]);
--
return Q.fcall(function () {
return [a, b];
})
.all();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.