Javascript 返回承诺数组的链接函数
我有一些类似于下面的东西,我想知道是否有一种“链式”的方法来做这件事,或者我是否偏离了目标,这代表了一种气味。谢谢Javascript 返回承诺数组的链接函数,javascript,node.js,promise,q,Javascript,Node.js,Promise,Q,我有一些类似于下面的东西,我想知道是否有一种“链式”的方法来做这件事,或者我是否偏离了目标,这代表了一种气味。谢谢 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(mor
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,如下所示
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 ]
根据您的承诺的结构,您还可以使用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");
})
根据您的承诺的结构,您还可以使用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.all([a, b]);
-