Skip to content

Instantly share code, notes, and snippets.

@danared
Created April 15, 2015 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danared/60eac629c1b55d88c29d to your computer and use it in GitHub Desktop.
Save danared/60eac629c1b55d88c29d to your computer and use it in GitHub Desktop.
function foo() {
someAsyncFunction(params, function(err, results) {
console.log(“one”);
});
console.log(“two”);
}
@guioconnor
Copy link

guioconnor commented Jun 21, 2016

From the tutorial:
"In the above example, we may think that the output would be: one two but in fact it might be two one because the line that prints “one” might happen later, asynchronously, in the callback. We say “might” because if conditions are just right, “one” might print before “two”."

Am I wrong in thinking in this example the conditions will never be "just right"?

The way the JS job queue works the asynchronous task will go to the end of the queue whereas the execution of foo() would already be queued, so no matter what someAsyncFunction does, it will always happen after the execution of line 5.

As a minimal reproduction case, this will always print two one:

function foo() {
    setTimeout(function() {
        console.log(“one”);
    }, 0);
    console.log(“two”);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment