Skip to content Skip to sidebar Skip to footer

While(count!==3) Fail To Check Callback State

I was learning Node with a tutorial called learnyounode from NodeSchool. This is about one of the 13 questions it provided: send 3 http get requests to 3 urls indicated by first 3

Solution 1:

JavaScript is single-threaded. It executes each execution context until it is finished, then it checks with the event loop to see if there are any new execution contexts queued up that it should execute (such as the callback of an asynchronous function).

The three getData calls all return immediately, then the while loop executes in the thread. The callbacks to http.get cannot execute until the current execution context is finished (until the while loop and everything after it have executed), so there is no way for count to increase, and no way for the loop to end.

The solution you have found works well, but to help with understanding you should realize that setTimeout and setInterval are asynchronous, so they do not block the thread. You could have solved this with something like:

getData(0);
getData(1);
getData(2);

setTimeout( function check_count ( ) { 
    if ( count !== 3 )
        return setTimeout( check_count, 100 );

    console.log(strArr[0]);
    console.log(strArr[1]);
    console.log(strArr[2]);

}, 100 );

That's not a nice solution, since it is arbitrarily checking every 100 ms instead of just waiting until the third callback executes and then immediately logging the results. It is just a demonstatrion of how you can "loop" without blocking the thread.

Post a Comment for "While(count!==3) Fail To Check Callback State"