Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Predictable sync vs. async in Node.js
var i = 0;
maybeSyncMaybeAsync(function(){
i++;
});
console.log("The value of i is", i);
@joepie91

This comment has been minimized.

Copy link
Owner Author

@joepie91 joepie91 commented Apr 19, 2015

This gist demonstrates why callbacks must always be called consistently - either synchronous 100% of the time, or asynchronous 100% of the time.

In this example, you can't predict what the output is going to be, because it's not clear whether the callback will be called synchronously or asynchronously - the increment could happen before or after the console.log, you simply don't know.

This is solved by consistently defining whether a callback will be called synchronously or asynchronously. More about this can be read here.

@AdamPflug

This comment has been minimized.

Copy link

@AdamPflug AdamPflug commented Apr 29, 2015

Alternatively this could just be rewritten so it doesn't matter :)

var i = 0;

console.log("The value of i is", i);

maybeSyncMaybeAsync(function(){
    i++;
});

In threaded languages because of write-locks it gets trickier (or impossible), but in JS you can usually avoid the issue by changing the order of statements so you don't depend on the callback being called synchronously or asynchronously.

@joepie91

This comment has been minimized.

Copy link
Owner Author

@joepie91 joepie91 commented Jul 12, 2015

@AdamPflug Right. The point was to demonstrate how an unpredictable API can cause issues, with an example that's as simple as possible to follow - whether this example can be changed isn't relevant, it's intentionally kept simple.

"Changing the order of statements" is not always possible, and sometimes simply incorrect. That's why it's so important to have a predictable API.

@saraf

This comment has been minimized.

Copy link

@saraf saraf commented Jul 29, 2015

to make this into a runnable example - async and sync versions of the function could be added -

//First try this
//This is asynchronous execution of the callback
function maybeSyncMaybeAsync(cb) {
        process.nextTick(cb);
}

/*
//Then try this definition
//This is synchronous
function maybeSyncMaybeAsync(cb) {
        cb();
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.