As JavaScript programmers we know that with ES6 promises, the notion of asyncronous programming has been built into JavaScript natively. Using promises guarantees that code is performed asynchronously.
But have you been aware that before ES6, the language itself did not have support for sync/async programming?
"That's not true!" you will probably say, "I have been using setTimeout and Ajax long before ES6! And you tell me that they are not async ??".
Well, the mentioned examples are clearly examples for async functionality, but: it is not functionality which is coming from the JavaScript language! Instead, it is functionality that comes from the environment in which JavaScript is executed (browser, nodejs...).
Indeed language-built-in constructs were not available.
So, how does setTimeout etc. this work?
On a low level this works because hardware interrupts signal events to the operating system which in turn then passes them to the JavaScript engine.
Takeaway: asyncronity is only achieved by using the environment's
async functionality - or by leveraging promises functionality, either
natively via ES6 promises or using promise libraries like Q.
Now let's go back to the original question from the title of this blog post: is every higher level function (a function that takes another function as an argument) async?
Having the background above in mind it should be obvious that the answer is no - because not all of such functions use async functionality from the environment.
Need examples? Check out Array.sort(compareFx) or String.replace(stringToReplace, replaceFx)...
And how can you find out if a function that you consume is async or not? There are only two possibilites: from the documentation or by digging into the code.
PS: Promises are not the end of the evolution of async programming in JavaScript. There is currently a proposal at stage 3 which deals with the introduction of async / await keywords in the language (btw: this is very similar to how the C# syntax looks).
No comments:
Post a Comment