B
B
baranovstas2022-01-21 11:13:41
AJAX
baranovstas, 2022-01-21 11:13:41

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()); // успешный промис, результат которого - массив пользователей

What is done inside func?
1) fetch returns a promise.
2) Promise makes a get request.
3) Receives a response - a Response object.
4) Then it resolves with this object.
5) In the meantime, await, before fetch, waits for all 4 items to complete in order to get the result of the promise and give this result to the const response.
6) Then we translate the result from the json string into an array - this also does not happen immediately, but with a certain delay.
7) Therefore, we add another await to wait for this operation as well.
8) And only after all the above items have been completed, then the return from func occurs.

But! Console output is synchronous code, which means it does not wait for all items (asynchronous operations) to be completed. In fact, for output to the console, the body of func should be like this:
async function func() {
  const response = undefined; // undefined, потому что синхронный код не ждёт, когда придет ответ от сервера, он тупо идет дальше...
  return undefined; // тут тоже возвращается undefined, потому что вывод не ждёт выполнения - await response.json()
}
console.log(func()); // успешный промис с результатом undefined

And here is the question itself - why is a promise displayed, the result of which is an array? Why is a promise not displayed with the result undefined? That is, it turns out that the output to the console has time to wait for all the operations of func, right?

Remark: I know that async returns a promise and resolves it with the value that comes after return (if there is a promise after return, then it is returned). And if the function does not have a specific return value, or in general, its body is empty, then a successful promise will be returned with the result undefined.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2022-01-21
@Rsa97

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 { … }

N
Nadim Zakirov, 2022-01-21
@zkrvndm

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);

Or, in relation to your code, do this:
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 question

Ask a Question

731 491 924 answers to any question