Accessing the value from a Promise using await in JavaScript (day-18/18_Day_Promises.md)

Open Beginner friendly
#995 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
1/5
Estimated time
Under an hour
Newbie friendliness
82/100
Issue type
Documentation
Clarity
Clearly specified
Activity status
Stale
Tech stack
javascript
Domain
documentation

Research direction

Open day-18/18_Day_Promises.md and review the section explaining await with the example in the issue. Update the lesson so it explains the top-level error and shows the async main() approach, then verify the example displays the expected value 4.

Written by the indexing model from the issue text.

Description

We want to access the value returned from an asynchronous function using await, but it causes an error when used at the top level.

const square = async function (n) {
  return n * n;
}

const value = await square(2); // ❌await is only valid in async functions and the top level bodies of modules
console.log(value);

CORRECT APPROACH:

const square = async function (n) {
  return n * n;
}

async function main() {
  const value = await square(2);
  console.log(value); //  4
}

main();
Dominant language
JavaScript
Stars
46.8k
Forks
10.5k
Avg merge
1m
Merged PRs (30d)
1

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Asabeneh/30-Days-Of-JavaScript

All issues in Asabeneh/30-Days-Of-JavaScript

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.