Reputation: 1439
I have wrote the following code:
async function imaAsyncFunction () {
console.log('1234');
let res = await setTimeout(()=>{console.log('10 sec');},10000);
console.log(res);
console.log('is After?!?');
}
imaAsyncFunction();
console.log('bla bla bla');
I was a little surprise that '1234' isn't printed at all. In addition the line console.log(res); was printed before the 10 seconds of timeout was finished, but i guess that the reason is that the code after await doesn't return a Promise. But, why does the code : console.log('bla bla bla'); was printed before both lines:
console.log(res);
console.log('is After?!?');
If we saw that the code doesn't postpone because of the setTimeout() so why both line of codes don't run before the function is finished and only after that the console.log('bla bla bla'); should run? What am I missing here?
Upvotes: 0
Views: 833
Reputation: 1075755
Does all async function code will run i a different thread?
No. async
functions, await
, and promises do not create or use different threads.
A promise doesn't make anything asynchronous on its own¹, it's just a way of observing the completion of something that's already asynchronous (like your timer callback, which uses the timer subsystem of your environment to call your timer callback later).
async
functions are "just" a way (a really, really useful way) to wait for promises to settle via syntax rather than by attaching fulfillment and rejection handlers using the .then
or .catch
methods.
I was a little surprise that the line console.log(res); was printed before the 10 seconds of timeout was finished, but i guess that the reason is that the code after await doesn't return a Promise.
setTimeout
doesn't return a promise, right. So await
doesn't wait for the timer callback to occur. See this question's answers for how you'd make a promise-enabled version of setTimeout
.
But, why does the code : console.log('bla bla bla'); was printed before both lines:
For the same reason: Your async
function returns a promise, and your code calling your async
function doesn't wait for that promise to be settled before moving on to the console.log('bla bla bla')
line.
Here's code that both uses a promise-enabled version of setTimeout
and waits for your async
function's promise to settle before doing the console.log
:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function imaAsyncFunction () {
let res = await delay(800); // 0.8s instead of 10s
console.log("Timer expired");
console.log(res); // undefined, since we haven't set a fulfillment value
console.log("is after");
}
imaAsyncFunction()
.then(() => {
console.log("bla bla bla");
})
.catch(error => {
console.error(error);
});
If you wanted the delay
function to return a fulfillment value, we could do this:
function delay(ms, value) {
return new Promise(resolve => setTimeout(() => {
resolve(value);
}, ms));
}
although in all standard environments (now), setTimeout
accepts a value to pass to its callback, so we can do just:
function delay(ms, value) {
return new Promise(resolve => setTimeout(resolve, ms, value));
}
function delay(ms, value) {
return new Promise(resolve => setTimeout(resolve, ms, value));
}
async function imaAsyncFunction () {
let res = await delay(800, 42); // 0.8s instead of 10s
console.log("Timer expired");
console.log(res); // 42
console.log("is after");
}
imaAsyncFunction()
.then(() => {
console.log("bla bla bla");
})
.catch(error => {
console.error(error);
});
In a comment you've said:
i still can't understand why both lines doesn't runs before the `console.log('bla bla bla');?
Here's your original code:
async function imaAsyncFunction () {
console.log('1234');
let res = await setTimeout(()=>{console.log('10 sec');},10000);
console.log(res);
console.log('is After?!?');
}
imaAsyncFunction();
console.log('bla bla bla');
When you run that code, here's what happens, in order:
imaAsyncFunction
is created.imaAsyncFunction()
is executed:
console.log('1234');
is executedsetTimeout(()=>{console.log('10 sec');},10000)
is executedsetTimeout
returns undefined
await
is reached: (Note: I'm skipping some details below for clarity.)
await p
, p
is a promise (or at least something like a promise). Since you've used it on undefined
instead, await
wraps undefined
in a promise as though it called Promise.resolve(undefined)
and used that as p
instead of undefined
.await
in the function is attached to p
as a handler for when p
is fulfilled (since you haven't used try
/catch
— which is fine — so there's no rejection handler). When you attach a fulfillment or rejection handler to a promise, you create a new promise that gets settled based on what happens to the original promise and, if relevant, what happens when the fulfillment or rejection handler is called. Let's call that new promise p2
.p
wouldn't be settled yet, but in this case it is, so the fulfillment handler (the rest of the code in imaAsyncFunction
, after the await
) is scheduled to run once the current synchronous work is completed. If p
weren't settled, this wouldn't happen yet (it would happen later, when p
is settled.)await
expressions in the function, the promise imaAsyncFunction
implicitly created (let's call it p3
) is resolved to p2
. That means that when p2
settles, the promise from imaAsyncFunction
is settled in the same way (it's fulfilled with the same fulfillment value as p2
, or rejected with the rejection reason from p2
).imaAsyncFunction
returns p3
.imaAsyncFunction
is done, so the next statement is executed: console.log('bla bla bla');
console.log(res)
and console.log('is After?!?')
.p2
with undefined
(since there's no return x
in the function).
p3
, since p3
was resolved to p2
. Doing that would scheduled execution of p3
's fulfillment handlers, but it doesn't have any — nothing used await
or .then
or .catch
, etc., on imaAsyncFunction()
's return value.¹ There's one caveat to that statement: When you attach a fulfillment or rejection handler to a promise, the call to that handler is always asynchronous even if the promise is already settled. That's because it would be asynchronous if the promise weren't settled, and it would be chaotic if the call to your handler was synchronous in some situations but asynchronous in others, so it's always done asynchronously. But that's literally the only thing about promises or async
functions that makes anything asynchronous, the rest just observes things that are already asynchronous.
Upvotes: 4