質問

Hi I have three function on nodejs.

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

Now function one and two are independent but function three should can only run when both function one and two finish execution. I don't want to nest function two inside function one as they can run in parallel; is it possible to do that in nodejs?

役に立ちましたか?

解決

Under such situations, I will make use of flags.

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

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

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

Once one completes execution, it will enter callback and check whether two() is completed. If so, it will run three().

Again if two completes execution first then it will check for oneComplete and run three()

This solution will not scale if you need to add more functions like one() and two(). For such a case, I suggest https://github.com/mbostock/queue

他のヒント

The best and most scalable solution you can use is to use async.auto(), which executes functions in parallel and respects the dependencies of each function:

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);
    }]
});

To run function asynchronously in javascript you can use setTimeout function.

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

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

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

In node.js you can use async library

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top