【发布时间】:2016-03-27 20:43:15
【问题描述】:
我想做一些准备工作,完成后我的其他工作应该开始,所以我将这些工作称为Q.all,但有些工作是异步的,这就是我想要的。
也许我的代码会让你理解我,在这个简单的例子中我想这样做:
- 为数组中的项目调用 foo2
- 在 foo2 中,我等待
10 * ams(假设这是一些已完成的工作),然后更改 res。 - 我想 foo2 正在运行然后
console.log(res),这意味着所有等待都结束了,所有项目都添加到 res。因此,在我的示例中, res 更改为 6。
这里是代码
var Q = require("q");
var res = 0;
function foo(a) {
res += a;
}
function foo2(a) {
// this is a simple simulation of my situation, this is not exactly what I am doing. In one word, change my method to sync is a little bit difficult
return Q.delay(10 * a).then(function() {
res += a;
});
}
// Q.all([1, 2, 3].map(foo)).done(); // yes, this is what I want, this log 6
// however, because of some situation, my work is async function such as foo2 instead of sync method.
Q.all([1, 2, 3].map(function(a) {
return foo2(a);
})).done();
console.log(res); // I want 6 instead of 0
【问题讨论】:
-
你不应该在你的 foo2 函数中 return Q.delay(10*a) 吗?
-
我需要用a在
foo2做一些更复杂的工作,但我只是举一个简单的例子,比如res += a,我只想指出foo2是异步的!跨度> -
你的问题到底是什么?
-
在 foo2 中,您没有返回承诺。你应该
return Q.delay(10*a)...,它会返回一个承诺。 -
是的,你有什么问题?
标签: node.js asynchronous synchronization promise