lydiahallie / javascript-questions

A long list of (advanced) JavaScript questions, and their explanations :sparkles:

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question 73 has wrong answer!

AliEl4eikh opened this issue · comments

This code will output:
Promise {: 'I made it'}

The getData function is an async function that returns a resolved promise with the value 'I made it!'. The await operator is used to wait for the promise to be resolved before returning the resolved value.

why did you choose Promise {}

Answer C is correct. It does not output Promise {<resolved>: "I made it!"}.
Or, better, it does but with a catch.

Just for reference, I'm reporting here below the code:

async function getData() {
  return await Promise.resolve('I made it!');
}

const data = getData();
console.log(data);

When logging data, the Promise object reference is printed. As a reference, it is a live-reference. So querying the reference (opening its properties) shows the latest properties.

As per the event-loop, the Promise has yet to be resolved when it gets printed. However, its resolutions is so fast for us (and the time between logging and "click-to-expand" is hence so short) that you likely won't be able to catch see the "pending phase".

Just for instance, here's a screenshot:

immagine

The first "<state>" is the one original one, when the reference got printed. The second is the one after the click.

Hope this explains :)

Is there a difference between these two functions?

async function getData() {
  return await Promise.resolve('I made it!');
}

async function getData2() {
  return Promise.resolve('I made it too!');
}

@miabrahams seen from outside, no differences. Async always returns a Promise. So as any thenable, it can be awaited or you can let it go (❄️).

So I guess that the only differences are the returned text and the function name eheh 😄

Thank you for your help!

Does return await Promise.resolve(...); have sense at all?

@contributorpw it doesn't have any sense in real world code and in this example too, but I guess it doesn't make any difference having it or not but increasing the difficulty of the question itself IMHO.

I guess this has been resolved, therefore closing this. Please feel free to reopen if this needs further clarification.