FAQ: Async Await - Writing async Functions

This community-built FAQ covers the “Writing async Functions” 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 Writing async Functions

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!

Hello, for the last step, at first i typed node app.js and it returned the right result. but then i saw the hint to suggest typing node someFileName.js, i tried and it returned an error like can’t find module someFileName(which i didn’t see either), why not use note app.js?

1 Like

how did you solve it

2 Likes

hello! Didnt understand entirely how the second point logs out ( 2. I bought ${beanType} beans because they were on sale ).

Is this because we invoke shopForBeans function when it is assigned to value variable?

7 Likes

I tried to use the setTimeout function inside the async await function from the 4th unit of asynchronous functions but it resulted in an error. Is it because it can only be used on newly written promises? If so, how could I set a timeout outside a promise?

This would be the code:

async function getBeans() { setTimeout(() => {console.log(1. Heading to the store to buy beans…); let value = await shopForBeans(); console.log(3. Great! I’m making ${value} beans for dinner tonight!);}, 2000) }

Thanks!

1 Like

My understanding of asynchronous code is that it allows Javascript code to continue while waiting for something to resolve.

But then in the async/await section there is a statement that the await keyword halts the execution of an async function until a promise is no longer pending? Is this saying that just the function halts but then there is other code going on after that?

I’m also not very clear on when the setTimeout() is used? I understand that it delays something a certain amount of seconds, but not when you should use it. In the examples it is sometimes used, sometimes not and I don’t know why.

Me neither… I thought that putting a function inside a variable just saves it there until we want to call it. Why is it behaving as if it was invoked?

2 Likes

This video, which was provided at the very beginning of this lesson does a great job explaining what goes on with asynchronous programming. It’s really worth a watch, but basically yes: the function halts and the rest of the code runs until the promise is resolved, then the function goes back in line to be executed.

setTimeout is only used here to simulate functins which would take a while to resolve. I don’t know how they’re usually used, but I guess you could think of creative ways to use it. Don’t worry about it, as here, they’re just emulating an effect.

Hope this helped somehow :slight_smile:

3 Likes

someFileName.js is a hint and is not telling you exactly what to do. The hint is assuming that you don’t know/remember how to run a JS file. It’s encouraging you to determine which file to run (app.js)

1 Like

The value of the resolved promise that shopForBeans() returns is stored in the value variable

1 Like

Someone please help me understand why the code below doesn’t work as I expect!
In the code below there’s a function with a long loop. I call it inside an async function. I expect the output like this:

calling myAsync
last line
countTo finished.
9

Instead I get this:
calling myAsync
countTo finished.
last line
9

the code:

const countTo = (num) => {
return new Promise(
(resolve, eject) => {
for (let i = 0; i < num; i++) {
let d = new Date();
let z = d.getMilliseconds();
}
console.log(‘countTo finished.’);
resolve(9);
}
);
};

const myAsyncFunc = async () => {
let x = await countTo(9876543);
console.log(x);
};

console.log(‘calling myAsync’);
myAsyncFunc();
console.log(‘last line’);

I think this has something to do with the event loop.

This is what I think is happening but I wouldn’t be surprised if I was wrong.

When the event flow gets to the point at which it is waiting for countTo to finish, it has queued console.log(‘last line’) to be run next.

counTo finishses (which logs "countTofinished" to the console) then it logs 'last line' then it hops back intomyAsyncFunc` and logs 9, since it was doing all this asynchronously

I do believe there is a bug in the code supplied in the library.js file.
As written we will never ever be able to have garbanzo beans for dinner (whatever they are!).
To fix this the result from Math.random() should be multiplied by 5 and not 4.
From the documentation from Math.random() …
“The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1)”

1 Like

I agree with this. I tested Math.random for fun just to be sure. This has happened once or twice in other lessons. Hard to spot because Math.random is a bit weird looking in JS in how you use it.

I cannot get passed the last step… I feel like I have tried everything. Please help me…

It doesn’t make a difference whether you put these lines before or inside the setTimeout() function does it?

let randomIndex = Math.floor(Math.random() * beanTypes.length);
let beanType = beanTypes[randomIndex];

I had the same question. The resolved value of shopForBeans promise is assigned to a variable, but why are we seeing the second point printed in the log? Does the Await keyword invoke the function?

1 Like

Also wondering the same thing, not seeing any answers in this thread - help please!

No, remember that when we declare a variable it’s associated with a value and because “value” it is assigned to “shopForBeans()” function, this makes that the computer need to run this function and when that happens in some part of the code the second message logs in the console:

console.log(2. I bought ${beanType} beans because they were on sale.);

const beanTypes = ["kidney", "fava", "pinto", "black", "garbanzo"];
let randomIndex = Math.floor(Math.random() * beanTypes.length);
let beanType = beanTypes[randomIndex];

I think this code (relevant parts extracted above) is fine as is:

Math.random() evaluates to a number from (and including) zero to (but excluding) one. By way of example, let’s say it evaluates to 0.99.

That number is then multiplied by the length of the beanTypes array, i.e. multiplied by 5. So for the example, 0.99 x 5 = 4.95.

That number is then rounded down. So for the example, 4.95 is rounded down to 4.

randomIndex can only be 0, 1, 2, 3, or 4.

beanType will therefore be:

beanTypes[0]: “kidney”
beanTypes[1]: “fava”
beanTypes[2]: “pinto”
beanTypes[3]: “black”
beanTypes[4]: “garbanzo”

Note that length is the number of elements in the array (i.e. if there is one element in the array the length of the array is 1). The length of the array is only zero if there are no elements in the array.

const exampleArray = [1, 2, 3, 4, 5];
console.log(exampleArray.length); // 5 is logged to console