2015-12-21 64 views
0

我想做一些準備工作,我的其他工作應在這些完成後開始,所以我稱這些工作爲Q.all,但有些工作是異步的,這是我想要的。如何使節點承諾方法同步?

可能是我的代碼將讓你瞭解我,在這個簡單的例子,我想這樣做:在陣列中的foo2的

    1. 呼叫foo2的爲項目,我等待10 * a毫秒(假設這做一些完成的工作),並改變水庫。
    2. 我想foo​​2正在運行,然後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 
    
  • +0

    你不應該回** ** Q.delay(10 *一)在foo2的FUNC? – Ludo

    +0

    我需要在'foo2'中做一些更復雜的工作,但我只是舉一個簡單的例子,比如'res + = a',我只想指出'foo2'是異步的! – roger

    +0

    你的問題到底是什麼? – jfriend00

    回答

    1

    在這種情況下,您的console.log聲明將在任何承諾有時間完成(在res被他們修改之前)之前運行,因爲它不在承諾塊內。

    看到這裏的承諾已經得到解決後的console.log將如何運行

    var Q = require("q"), 
        res = 0; 
    
    
    function foo(a) { res += a; } 
    
    function foo2(a) { 
        return Q 
        .delay(10 * a) 
        .then(function() { res += a; }); 
    } 
    
    Q.all([1, 2, 3].map(function(a) { return foo2(a); })) 
    .then(function(){ console.log(res) }) 
    .done();