FAQ: Async Await - The await Operator

This community-built FAQ covers the “The await Operator” exercise from the lesson “Async Await”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Asynchronous JavaScript

FAQs on the exercise The await Operator

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

This might just be flying over my head, but I’m a bit confused with the output of this exercise.

From what I understand async… await lets us control the flow of our tasks by halting the execution of our async function until a given promise is resolved. Ok cool I can get that.

However, while working on the exercise and calling both the native promise (nativePromiseDinner()) and async (announceDinner()) functions together I see them execute identically.

There are 2 ways that this could make sense to me:

  1. After looking over the brainstormDinner Promise, each log is individually resolving the Promise, therefore completing the await, then returning to the next log.

  2. I don’t understand async… await and the exercise.

1 Like

Hi @sasquiche you are right that await lets us control the flow of our tasks by halting the execution of our async function until a given promise is resolved.

So if we declare that:

let resolvedValue = await brainstormDinner();

in the announceDinner function, we have to wait for the brainstormDinner promise to resolve.

Now, as you rightly mention, both the native promise (nativePromiseDinner()) and async (announceDinner()) functions execute identically. This is because the exercise is meant to show us that the async wait method is identical to using native promises.

Finally, looking over the brainstormDinner Promise, each log is is not resolving the Promise. Essentially, the promise first logs various messages, then resolves with the meal you decide to cook i.e

resolve('beans')

Hope that explanation helps.

1 Like

@textninja83556 This was the explanation I was looking for. Thank you very much.

2 Likes

function nativePromiseDinner() {
brainstormDinner().then((resolve) => {
console.log(I'm going to make ${resolve} for dinner.);
})
}
nativePromiseDinner() ;

// async/await version:
async function announceDinner() {
// Write your code below:
let meal = await brainstormDinner();
console.log(I'm going to make ${meal} for dinner.);
}

announceDinner()

I have called both, promises and async await at same tme and i got this as op why?faq

what i have understood is its because both of them are asynchronous function.so when compiler read nativePromiseDinner() , it do not stop and wait for it’s execution to be completed, rather it is running in background and compiler move to next function call which is announceDinner(), thus our both functions are running at same time in background with delay of 1sec(1000) that is why we get same statement 2 time, P.S sorry for my bad English :smiley:

In the previous lesson, they said:

async functions always return a promise.

So why do we need to use a promise anyway ?
Can’t we just do an async function and an await outside of it ?

This video on YouTube was linked earlier in the course. It’s about a half hour but really worth a watch to get exactly what is going on.

hi, I looked at the code solution, since i wanted to know what went wrong, since my program was working fine and to expectations when i did “node app.js”

however, it was the exact code (except one comment)

what on earth happened? it’s clearly a glitch since the comment was single line and no other code being affected…
i am now not sure if this glitch will happen again

Hi All,
I have re-written the brainstormDinner function as below. But it’s returning ‘undefined’ value instead of ‘beans’. Can anybody review my code please?
@midlindner @mtf

Original code (as given by Codecademy):

> 
> const brainstormDinner = () => {
>   return new Promise((resolve, reject) => {
>   console.log(`I have to decide what's for dinner...`)
>   setTimeout(() => {
>     console.log('Should I make salad...?')
>     setTimeout(() => {
>       console.log('Should I make ramen...?')
>       setTimeout(() => {
>         console.log('Should I make eggs...?')
>         setTimeout(() => {
>           console.log('Should I make chicken...?')
>           resolve('beans')
>         }, 1000)
>       }, 1000)
>     }, 1000)
>   }, 1000)
> })
> }
> 
> async function announceDinner() {
>     let meal = await brainstormDinner(); 
>     console.log(`I'm going to make ${meal} for dinner.`);
>   }
> 
> announceDinner();
> ```

My code:

async function brainstormDinner2(){

    console.log(`I have to decide what's for dinner...`);

    setTimeout(() => {

      console.log('Should I make salad...?');

      setTimeout(() => {

        console.log('Should I make ramen...?');

        setTimeout(() => {

          console.log('Should I make eggs...?');

          setTimeout(() => {

            console.log('Should I make chicken...?');

            return 'beans';

          }, 1000);

        }, 1000);

      }, 1000);

    }, 1000);

  };

async function announceDinner() {

    let meal = await brainstormDinner2(); 

    console.log(`I'm going to make ${meal} for dinner.`);

  }

announceDinner();

Output (node app.js):

I have to decide what’s for dinner…
I’m going to make undefined for dinner.
Should I make salad…?
Should I make ramen…?
Should I make eggs…?
Should I make chicken…?

1 Like

My second question is:
The lesson says that “Await is an operator: it returns the resolved value of a promise.”
So, what will happen if there’s a reject in place of a resolve?
@midlindner @mtf

I’m pretty confused by this whole module but should it be resolve(‘beans’) instead of return ‘beans’;?

Hi

Quick question. Till this lesson(module) i am figuring out we should be writing our code using
async… await :+1:

Don’t need to use callbacks :-1:
Don’t need to use Promises :-1:

I want to do more practice so i can become more easy with this way of coding. Can someone please guide where i can find more exercises related to this.

Kind Regards

‘What is the benefit of using async function rather than existing promise?’

Hello World! everyone!
I have question on ‘what is the benefit of using async function rather than existing promise.’
please check below codes first!

const myPromise = function() {
    return new Promise((res,rej) => {
        res('I am reswolved now!');
    });
};
// async version
async function asyncFuncExample(){
    let resolvedValue = await myPromise();
    console.log(resolvedValue);
  }
asyncFuncExample(); // Prints: I am resolved now!

here explained as below:

Within our async function, asyncFuncExample(), we use await to halt our execution until myPromise() is resolved and assign its resolved value to the variable resolvedValue. Then we log resolvedValue to the console. We’re able to handle the logic for a promise in a way that reads like synchronous code.

but I think just using promise as below also work.
e.g) when using promise.then().then()
first .then() is waiting for promise to be resolved/
when promise is resolved, first then() will be executed.
and when first .then() return new promised valude
second .then() receive it and executed.
below is the simple code that I think that work just as above async syntax without creating any new function.

// promise  version
myPromise()
.then((res) => console.log(res))

it seems that using promise.then() is much easier to read and more simple.
Still, don’t know why using complicate async syntax and make it complex.
Is there anything I missed or misunderstood?
Is there any benefit for using async instead of normal promise?

Also when check provided app.js from here.
It seems that there are no big differences between using existing promise syntax and async function.
For me, it seems using async function just making another variable and cause code to be more complex…
please anyone help me with this.
thank you!

const brainstormDinner = require('./library.js')

// Native promise version:
function nativePromiseDinner() {
  brainstormDinner().then((meal) => {
      console.log(`I'm going to make ${meal} for dinner.`);
  })
};
nativePromiseDinner();

// async/await version:
async function announceDinner() {
  // Write your code below:
  const meal = await brainstormDinner();
  console.log(`I'm going to make ${meal} for dinner.`);
}
announceDinner();

But async function always return promise one of below 3 ways:

  1. If nothing returned from async function, it will return promise with a resolved value of undefined.
  1. If there is non-promise value returned, it will return a promise with a resolved to that value.
  1. If a promise returned, it will simply return that promise.

so i think within async function there is a return value ‘beans’,
isn’t is suppose to receive that value with resolve()?