Promises chapter

In the task three of the promise chapiter which speak about the await operator i had used the await in my function and in the second time i had’nt used it .but the function execute the same result this is my code :

I had use the await operator in the function :
function nativePromiseDinner() {
const meal = await
  brainstormDinner().then((meal) => {
	  console.log(`I'm going to make ${meal} for dinner.`);
  })
}
I exclude th await operator from the function: 
function nativePromiseDinner() {
  brainstormDinner().then((meal) => {
	  console.log(`I'm going to make ${meal} for dinner.`);
  })
}

Hi,

await has to do with order of operations and fulfilling promises. For example it’s useful when you need certain data to be loaded for some code block to work. I suggest playing in the console with this idea.

An example, you make a function that resolves after 4 seconds and call it resolveAfter4Seconds().

If you write

resolveAfter4Seconds("4 seconds have passed")
    .then(console.log("I wonder how this will appear"));

You will get

I wonder how this will appear
(immediately)
Promise { : “pending” }

but if you write

await resolveAfter4Seconds("4 seconds have passed")
    .then(console.log("I wonder how this will appear"));

you will get

I wonder how this will appear
(… after 4 seconds)
“4 seconds have passed”

I borrowed the function of 4 seconds from mdn and it looks like this:

function resolveAfter4Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 4000);
  });
}

You have to play around with it to convince yourself of the subtle differences.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.