Answer the question
In order to leave comments, you need to log in
How does console output wait for an async function to execute?
Hello. There is the following code:
async function func() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
return await response.json();
}
console.log(func()); // успешный промис, результат которого - массив пользователей
async function func() {
const response = undefined; // undefined, потому что синхронный код не ждёт, когда придет ответ от сервера, он тупо идет дальше...
return undefined; // тут тоже возвращается undefined, потому что вывод не ждёт выполнения - await response.json()
}
console.log(func()); // успешный промис с результатом undefined
Answer the question
In order to leave comments, you need to log in
async func()
always returns a promise.
And it is this promise with the pending status that is displayed in the console.
After the fetch and json are completed, the promise status will change to fulfilled and a value will be added to it.
Here is the console output immediately after console.log:
Promise { <state>: "pending" }
If we expand this object after some time, we will see that its status has already changed (you remember that a live object is output to the console by reference):
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Array(10) [ {…}, {…}, {…}, … ]
<prototype>: Promise.prototype { … }
An asynchronous function always returns a promise, you do not display the result with your console.log, but stupidly a promise from the function. Further, it is quite possible to run asynchronous code in the console, try right now to drive in the console:
response = await (await fetch('https://jsonplaceholder.typicode.com/users')).json();
console.log(response);
async function func() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
return await response.json();
}
console.log(await func());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question