DEV Community

Discussion on: Javascript: How to access the return value of a Promise object

Collapse
 
ramonak profile image
Katsiaryna (Kate) Lupachova

because "address" in not a function here, but a variable to which the return value of the fetch request is assigned to

Collapse
 
smallbasic profile image
small-basic

thanks for the reply.

Just one last question, if the "address" is a variable which stores the result of the fetch query, then what is triggering the fetch call ?.

Thread Thread
 
ramonak profile image
Katsiaryna (Kate) Lupachova

once the interpreter ((like the JavaScript interpreter in a web browser) ) reaches the code with the fetch() function, it adds it to the call stack list. We just assign the result (the return value) of this async function in order to have access to it later.

The call stack order is really easy to test. If we update the code like this:

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    console.log("FETCH RETURN");
    return user.address;
  });

const printAddress = async () => {
  console.log("PRINT ADDRESS");
//   const a = await address;
//   console.log(a);
};

console.log("RUN");
printAddress();
Enter fullscreen mode Exit fullscreen mode

The result in the console will be:
RUN
PRINT ADDRESS
FETCH RETURN

The fetch function is being executed without any additional trigger or call. But we get its result after all other functions because fetch takes more time to complete its job. And as fetch is an asynchronous function, it's not blocking other functions.

Thread Thread
 
smallbasic profile image
small-basic

thank you so much