I read some questions about this topic here at stackoverflow but none of them seems to answer my doubts.
I know how to create async functions using process.nextTick:
var async_function = function(val, callback){
process.nextTick(function(){
callback(val);
});
};
I've also read about Promise, but how do you write async non-blocking functions without using libraries such as process, Promise, etc?
What's the native way? I thought first on this approach:
var async = function(val, cb) {
cb(val);
}
However, that function blocks:
async(3, function(val) {
console.log(val);
});
console.log(4);
// returns:
3
4
So what's the correct implementation? How could I write async functions without depending on those libraries?
You can use setTimeout
- it's native function like a delay.
Break up your function's work into chunks and use process.nextTick
to queue the next chunk once the current one has completed. That way you allow other queued callbacks to be executed between each chunk of work. When all chunks have completed, call the callback that was passed into your function as a parameter.
The above is assuming your function is not calling existing async APIs which would naturally make your function async without doing anything special.
On Node.js, you need to be using process.nextTick
. In the browser, you can use the postMessage
hack which is much more efficient than setTimeout(function(){},0)
.
Here is a cross-browser implementation of the postMessage
hack: https://github.com/timoxley/next-tick/blob/master/index.js