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