2014-02-14 156 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功能,而不是使用外部節點模塊。不過謝謝。 :) –