if you want to remove an article from website contact us from top.

    await is only valid in async functions and the top level bodies of modules

    James

    Guys, does anyone know the answer?

    get await is only valid in async functions and the top level bodies of modules from EN Bilgi.

    NodeJS Await is Only Valid in Async Function

    Implement a “top-level” async function in Node when there is no async main method

    CodeProject SenseAI

    All Message Boards...

    Application Lifecycle>

    Running a Business Sales / Marketing

    Collaboration / Beta Testing

    Work Issues

    Design and Architecture

    Artificial Intelligence

    ASP.NET JavaScript Internet of Things C / C++ / MFC> ATL / WTL / STL Managed C++/CLI C# Free Tools

    Objective-C and Swift

    Database Hardware & Devices> System Admin Hosting and Servers Java Linux Programming

    .NET (Core and Framework)

    Android iOS Mobile WPF Visual Basic Web Development

    Site Bugs / Suggestions

    Spam and Abuse Watch

    Source : www.codeproject.com

    javascript

    I wrote this code in lib/helper.js var myfunction = async function(x,y) { .... return [variableA, variableB] } exports.myfunction = myfunction; and then I tried to use it in another file var

    await is only valid in async function

    Ask Question

    Asked 4 years, 2 months ago

    Modified 4 months ago

    Viewed 527k times 282

    I wrote this code in lib/helper.js

    var myfunction = async function(x,y) {

    ....

    return [variableA, variableB]

    }

    exports.myfunction = myfunction;

    and then I tried to use it in another file

    var helper = require('./helper.js');

    var start = function(a,b){

    ....

    const result = await helper.myfunction('test','test');

    }

    exports.start = start;

    I got an error

    "await is only valid in async function"

    What is the issue? javascript node.js Share

    edited Sep 4, 2020 at 19:35

    patridge 26k17 17 gold badges 90 90 silver badges 131 131 bronze badges

    asked Mar 22, 2018 at 15:29

    j.doe 3,7474 4 gold badges 18 18 silver badges 24 24 bronze badges 4

    Well, the issue is that await can only be used inside an async function. That is, await makes a function asynchronous, so it must be declared as such. –

    Pointy

    Mar 22, 2018 at 15:30

    What is the current error? –

    acdcjunior

    Mar 22, 2018 at 15:43

    still the same, SyntaxError: await is only valid in async function –

    j.doe

    Mar 22, 2018 at 15:45

    You need to share more context about your code. –

    Ele

    Mar 22, 2018 at 15:54

    2

    Possible duplicate of How do I return the response from an asynchronous call? –

    Liam

    Mar 22, 2018 at 16:02

    Show 1 more comment

    12 Answers

    343

    The error is not refering to myfunction but to start.

    async function start() {

    ....

    const result = await helper.myfunction('test', 'test');

    } // My function

    const myfunction = async function(x, y) {

    return [ x, y, ]; } // Start function

    const start = async function(a, b) {

    const result = await myfunction('test', 'test');

    console.log(result);

    } // Call start start(); Expand snippet

    I use the opportunity of this question to advise you about an known anti pattern using await which is : return await.

    WRONG

    async function myfunction() {

    console.log('Inside of myfunction');

    }

    // Here we wait for the myfunction to finish

    // and then returns a promise that'll be waited for aswell

    // It's useless to wait the myfunction to finish before to return

    // we can simply returns a promise that will be resolved later

    // useless async here

    async function start() {

    // useless await here

    return await myfunction();

    } // Call start (async() => {

    console.log('before start');

    await start();

    console.log('after start');

    })(); Expand snippet

    CORRECT

    async function myfunction() {

    console.log('Inside of myfunction');

    }

    // Here we wait for the myfunction to finish

    // and then returns a promise that'll be waited for aswell

    // It's useless to wait the myfunction to finish before to return

    // we can simply returns a promise that will be resolved later

    // Also point that we don't use async keyword on the function because

    // we can simply returns the promise returned by myfunction

    function start() {

    return myfunction();

    } // Call start (async() => {

    console.log('before start');

    await start();

    console.log('after start');

    })(); Expand snippet

    Also, know that there is a special case where return await is correct and important : (using try/catch)

    Are there performance concerns with `return await`?

    Share

    edited Jun 11, 2020 at 17:48

    answered Mar 22, 2018 at 15:29

    Orelsanpls 20.6k4 4 gold badges 36 36 silver badges 61 61 bronze badges

    But this is not working, I updated my code. I still get the same error –

    j.doe

    Mar 22, 2018 at 15:35

    @j.doe I've added a snippet –

    Orelsanpls

    Mar 22, 2018 at 15:53

    2

    Thanks, I found my problem. I was trying to do it inside a callback is the start() function. The solution was : const start = async function(a, b) { task.get(options, async function (error, result1) { const result = await myfunction('test', 'test'); –

    j.doe

    Mar 22, 2018 at 16:00

    Considering that Node is a single threaded. Doesn't it decreases the request per minutes and also increases the delay in between fullfilling requests. –

    Rishabh Dhiman

    Sep 8, 2019 at 15:40

    1

    It's worth mentioning that in the "CORRECT" example, it isn't necessary to declare start as an async function (although some will chose to do so anyways, in order to be more explicit) –

    Gershom Maes

    Jan 7, 2020 at 20:02

    Show 1 more comment 27

    To use await, its executing context needs to be async in nature

    As it said, you need to define the nature of your executing context where you are willing to await a task before anything.

    Just put async before the fn declaration in which your async task will execute.

    var start = async function(a, b) {

    // Your async task will execute with await

    await foo()

    console.log('I will execute after foo get either resolved/rejected')

    Source : stackoverflow.com

    Fix

    The error "await is only valid in async functions and the top level bodies of modules" occurs when the `await` keyword is used inside of a function that was not marked as `async`. To solve the error, mark the directly enclosing function as `async`.

    Fix - Await is only valid in async function Error in NodeJS

    Borislav Hadzhiev Sat Mar 12 2022 2 min read

    Photo by Kevin O'Connor

    Fix - Await is only valid in async function Error in NodeJS #

    The error "await is only valid in async functions and the top level bodies of modules" occurs when the await keyword is used inside of a function that was not marked as async. To solve the error, mark the directly enclosing function as async.

    Here are 2 examples of how the error occurs.

    index.js

    // 👇️ Cause: Function not marked as async

    function getNum() {

    // ⛔️ Error: SyntaxError: await is only valid

    // in async functions and the top level bodies of modules

    const num = await Promise.resolve(100);

    return num; }

    // 👇️ Cause: Using top level await without setting

    // `type` to `module` in `package.json`

    const result = await Promise.resolve(42);

    The first cause of the error is - using the await keyword inside of a function that was not declared as async.

    To solve this, we have to mark the directly enclosing function as async.

    index.js

    // ✅ now marked as async

    async function getNum() {

    const num = await Promise.resolve(100);

    return num; }

    If you're getting the error for using top-level await, scroll down to the package.json section of the article.

    A very common cause of the error is forgetting to set an inner function as async, e.g. the ones we pass to methods like forEach(), map(), etc.

    Note that the directly enclosing function of the one that uses the await keyword has to be marked as async.

    index.js

    async function loopNums() {

    const nums = [3, 5, 7];

    nums.forEach(num => {

    // ⛔️ SyntaxError: await is only valid

    // in async functions and the top level bodies of modules

    await Promise.resolve(num);

    }); }

    We marked the loopNums function as async, but we're using the await keyword inside of the function we passed to the forEach() method.

    Instead, we should have marked the function we passed to forEach as async.

    index.ts

    function loopNums() {

    const nums = [3, 5, 7];

    nums.forEach(async num => {

    await Promise.resolve(num);

    }); }

    Now, the function we passed to the forEach method is async, so we are able to use the await keyword in it.

    The directly enclosing function has to be marked async for us to be able to use the await keyword.

    If you're trying to use the await keyword on the top level of your Node.js application, make sure to set the type attribute to module in your package.json file.

    If you don't have a package.json file, create one by using the npm init -y command (only if you don't have one already).

    Open the package.json file at the root directory of your project and set the type attribute to module.

    package.json { "type": "module",

    // ... your other settings

    }

    Now you can use top level await in your Node.js code.

    index.ts

    const result = await Promise.resolve(42);

    console.log(result); // 👉️ 42

    Use the search field on my Home Page to filter through my more than 1,000 articles.

    Source : bobbyhadz.com

    Do you want to see answer or more ?
    James 1 month ago
    4

    Guys, does anyone know the answer?

    Click For Answer