2014-02-14 157 views
0

您好我有三个nodejs函数。Nodejs函数依赖关系

var one = function(){ implementation }; 
var two = function(){ implementation }; 
var three = function(){ implementation }; 

现在函数一和二是独立的,但函数三应该只能在函数一和二完成执行时才能运行。我不想在函数内嵌套函数2,因为它们可以并行运行;有没有可能在nodejs中做到这一点?

+1

你如何调用它们? “完成执行”是什么意思? – zerkms

+0

例如函数三是回调函数。 功能(三){0} {0} two(); //并且当一个和两个完成时,则返回 three(); } –

回答

2

在这种情况下,我会利用标志。

(function() { 
    //Flags 
    oneComplete = false; 
    twoComplete = false; 

    one(function() { 
    oneComeplete = true; 
    if (oneComplete && twoComeplete) { 
     three(); 
    } 
    }); 

    two(function() { 
    twoComeplete = true; 
    if (oneComplete && twoComeplete) { 
     three(); 
    } 
    }); 
})(); 

一旦完成执行,它将进入回调并检查是否完成了两个()。如果是这样,它将运行三()。

同样如果两个执行完第一个那么它会检查oneComplete和运行三个()

,如果你需要添加更多的功能,如一个该解决方案将无法扩展()和两个()。对于这样的情况下,我建议https://github.com/mbostock/queue

+0

感谢您添加最简单的解决方案。 –

0

要在JavaScript中异步运行函数,您可以使用setTimeout函数。

function one(){ 
console.log(1); 
} 

function two(){ 
console.log(2); 
} 

setTimeout(function(){ one(); }, 0); 
setTimeout(function(){ two(); }, 0); 

在node.js中可以使用异步库

var http = require('http'); 
var async = require("async"); 

http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'}); 

    async.parallel([function(callback) { setTimeout(function() { res.write("1st line<br />");}, Math.round(Math.random()*100)) }, 
    function(callback) { setTimeout(function() { res.write("2nd line<br />");}, Math.round(Math.random()*100)) }, 
    function(callback) { setTimeout(function() { res.write("3rd line<br />");}, Math.round(Math.random()*100)) }, 
    function(callback) { setTimeout(function() { res.write("4th line<br />");}, Math.round(Math.random()*100)) }, 
    function(callback) { setTimeout(function() { res.write("5th line<br />");}, Math.round(Math.random()*100)) }], 
    function(err, results) { 
     res.end(); 
    } 
); 
}).listen(80); 

Demo

2

你可以使用的最好的和最可扩展的解决方案是使用async.auto(),这在并行执行功能和尊重每个功能的相关性:

async.auto({ 
    one: function(callback) { 
     // ... 
     callback(null, some_result); 
    }, 
    two: function(callback) { 
     // ... 
     callback(null, some_other_result); 
    }, 
    three: ['one', 'two', function (callback, results) { 
     console.log(results.one); 
     console.log(results.two); 
    }] 
}); 
+0

+1这个好的解决方案,但我更喜欢只使用核心nodejs功能,而不是使用外部节点模块。不过谢谢。 :) –