0
我想做一些准备工作,我的其他工作应在这些完成后开始,所以我称这些工作为Q.all
,但有些工作是异步的,这是我想要的。如何使节点承诺方法同步?
可能是我的代码将让你了解我,在这个简单的例子,我想这样做:在阵列中的foo2的
- 呼叫foo2的为项目,我等待
10 * a
毫秒(假设这做一些完成的工作),并改变水库。 - 我想foo2正在运行,然后
console.log(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
你不应该回** ** Q.delay(10 *一)在foo2的FUNC? – Ludo
我需要在'foo2'中做一些更复杂的工作,但我只是举一个简单的例子,比如'res + = a',我只想指出'foo2'是异步的! – roger
你的问题到底是什么? – jfriend00