B
B
baranovstas2022-01-14 13:41:48
AJAX
baranovstas, 2022-01-14 13:41:48

How exactly does await get the result of a promise?

Hello. There is the following code:

(async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  console.log(response); // экземпляр объекта Response
})();

Question: how exactly does await assign the result of a fulfilled promise to a variable? Look, await is waiting for the promise to be fulfilled, it has waited, that is, we have a resolved instance of the Promise object. But... how exactly does await manage to take and get the result of this resolved instance like this and put it into a variable? Well, I just don’t see any other way here at all, how to access the property and take the value of this property. But it's not available, is it? I don’t want to understand it just like that, well, they say, this is how await works and that’s it. I want to dig deeper. And I know that async / await are built on promises and generators, but I still don’t understand how await manages to get the result of a Promise. Explain, please?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2022-01-14
@Fragster

Maybe it will become clearer if we add a little from the classic example:

function fetch(addr) {
  return new Promise((resolveFunction) => {
    setTimeout(() => {
      resolveFunction('addr response') // вызываем функцию, которая прилетела параметром
    }, 3000)
  })
}

(async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  console.log(response); // результат, который передали в resolveFunction
})();

Very roughly speaking, everything comes back to callbacks, or rather, to calling a function with a parameter at the end of the process.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question