D
D
Devgru2011-03-22 15:46:57
JavaScript
Devgru, 2011-03-22 15:46:57

Node.js: wait for two callbacks to complete and start the third one

I need to wait for 2 asynchronous requests (let's say fs.readFile and fs.stat) to respond and after both are done call some function.
What is the easiest way to create an adequate semaphore for this?

Or would you recommend starting the execution of the second asynchronous request only after the completion of the first one?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anatoly, 2011-03-22
@taliban

I made myself a banal queue. But this is in the client zhs. I needed to make several Ajax requests, and then when everything was over, execute one resultant (or not one), as a result, this crap came out:


var queryQueue = {
  counter: 0,
  finishEvents: [],
  push: function()
  {
    queryQueue.counter ++;
  },
  pop: function()
  {
    queryQueue.counter --;
    if( queryQueue.counter === 0 )
    {
      queryQueue.fireFinish();
    }
  },
  addFinishEvent: function( func )
  {
    queryQueue.finishEvents.push( func );
    if( queryQueue.counter === 0 )
    {
      queryQueue.fireFinish();
    }
  },
  fireFinish: function()
  {
    var func = null;
    while( func = queryQueue.finishEvents.pop() )
    {
      func();
    }
  }
}

As a result, when we do something, we execute quertQueue.push() when the action is over queryQueue.pop()
after all pushes we add handlers that will be executed at the end of all requests (or immediately if the queue is empty).
The option with flags was immediately dismissed, since when changing the number of tasks, you will have to change the number of flags.

P
Pavlo Ponomarenko, 2011-03-22
@TheShock

Topic on Habré: " After all asynchronous calls "

D
Dzuba, 2011-03-22
@Dzuba

And the banal option with two boules does not suit you?


var firstCallFinished = false;
var secondCallFinished = false;

... вызов асинхронов ...

function firstCallback()
{
    firstCallFinished = true;
    checkFunction();
}
function secondCallback()
{
    secondCallFinished = true;
    checkFunction();
}

function checkFunction()
{
    if (!firstCallFinished || !secondCallFinished)
        return;
    firstCallFinished = false;
    secondCallFinished = false;
    ... тут вызов нужной Вам функции ...
}

F
Fedor Indutny, 2011-03-22
@donnerjack13589

github.com/creationix/step
Try this library

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question