2015-12-21 60 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();