Does making a function async make it asynchronous?
It depends on what you mean by asynchronous.
Let's consider a slightly different version of your code:
async function f(){
let rPromise = first();
let dPromise = sec(r);
let r = await rPromise;
let dPromise = await dPromise;
return d;
}
Here because we don't await
the first promise until after the second promise is started, the two might be both waited on at the same time (they might not if first()
returned a completed promise quickly enough). The two may be doing stuff at the same time. rPromise
might complete before dPromise
or it might complete after it. However, they will only be doing stuff at the same time if what they are doing is something (like waiting on I/O response from a web service) that happens outside of JavaScript itself.
In some other languages/frameworks we might expect two threads to be running here, possibly on different cores. In JavaScript there is only one thread and the bit of the code that is actually running in JavaScript (rather than the web access library that the JavaScript is waiting for a response from, or the timer that triggers a delay, or whatever) will only ever be running in first()
or sec()
, but never in both at the same time. If what one if them is internally await
ing returns while the other is dealing with what it await
ed on, then the further processing won't happen until the other function is finished.
This is asynchronous
(the two are not happening in a fixed sequence where one must happen before the other).
It is not though multithreaded, and the actual JavaScript code in each does not happen at the same time, which is what would be termed asychronous
in some other contexts.
But in some older article I read we can't create an asynchronous function in JavaScript.
Well, firstly, until recently we couldn't even create this sort of asynchronous code in JavaScript until recently, though we could create promises by other means.
Secondly, while it's asynchronous it's not what some people coming from other languages and frameworks would think of as asynchronous, where asynchronicity is primarily delivered through multi-threading which has both abilities JavaScript lacks, but also pitfalls that it also lacks.