0

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?

Community
  • 1
  • 1
jviotti
  • 17,881
  • 26
  • 89
  • 148
  • I know you really don't want an API, but I recently stumbled upon this video on reactive extensions for javascript, and found it fascinating. Why reinvent the wheel? http://channel9.msdn.com/Blogs/codefest/DC2010T0100-Keynote-Rx-curing-your-asynchronous-programming-blues – Mike Panter Nov 28 '12 at 03:06
  • Keep in mind that "async" and "non-blocking" are not the same thing. By following the instructions in these answers (`process.nextTick`, `setTimeout`, etc) the callback will fire asynchronously, but once it starts running, it will still be blocking the event loop. – Michelle Tilley Nov 28 '12 at 03:16

3 Answers3

1

You can use setTimeout - it's native function like a delay.

AChudov
  • 214
  • 1
  • 4
  • It's worth noting that, if you're only targeting Node.js, `process.nextTick(func)` is much more efficient than `setTimeout(func, 0)` and do, for most practical purposes, the exact same thing. See http://nodejs.org/docs/latest/api/process.html#process_process_nexttick_callback – Michelle Tilley Nov 28 '12 at 03:15
  • Thank you. You are right, but the question was - how to do async function on pure js. – AChudov Nov 28 '12 at 03:26
  • Definitely! The comment was for other readers, not for you. :) – Michelle Tilley Nov 28 '12 at 03:34
0

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

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

JP Richardson
  • 38,609
  • 36
  • 119
  • 151