链接返回承诺数组的函数
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();
https://github.com/kriskowal/q#the-middle
相关文章:
- 使用jQuery浏览函数数组
- coffescript/javascript函数数组的行为真的很奇怪
- 返回多个变量的 JavaScript 函数:数组与对象.最佳实践是什么
- 如何在 JavaScript 中动态地编写可迭代的函数数组
- JavaScript 自包含函数数组访问自我索引
- 如何在javascript中调用函数数组的索引号
- 从外部函数(数组)了解返回函数(x)
- Javascript函数数组
- 引用函数数组中的另一个函数
- 文本框搜索/Javascript函数数组**不对应**
- 返回一个函数数组
- selenium-webdriver 将函数数组作为参数传递给 executeScript
- 70%的时间运行JavaScript函数,从函数数组中随机选择
- 如何循环函数数组并在单击时一次执行一个
- 如何在 Javascript 命名空间脚本中创建函数数组
- 创建函数数组
- 在 Jscript 中为 Q.all() 构建一个动态函数数组
- 打印函数数组的函数名称
- 循环遍历函数数组 - 对象不支持此属性或方法 (IE8)
- 将函数数组传递给另一个函数