Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Open
@RahulKumar2340029

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();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

        AltStyle によって変換されたページ (->オリジナル) /