Answer the question
In order to leave comments, you need to log in
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
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();
}
}
}
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;
... тут вызов нужной Вам функции ...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question