Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: SyntaxError: await is only valid in async function

I am on Node 8 with Sequelize.js

Gtting the following error when trying to use await.

SyntaxError: await is only valid in async function

Code:

async function addEvent(req, callback) {
    var db = req.app.get('db');
    var event = req.body.event

    db.App.findOne({
        where: {
            owner_id: req.user_id,
        }
    }).then((app) => {

                let promise = new Promise((resolve, reject) => {
                    setTimeout(() => resolve("done!"), 6000)

                })

               // I get an error at this point 
               let result = await promise;

               // let result = await promise;
               //              ^^^^^
               // SyntaxError: await is only valid in async function
            }
    })
}

Getting the following error:

               let result = await promise;
                            ^^^^^
               SyntaxError: await is only valid in async function

What am I doing wrong?

like image 571
user1107173 Avatar asked Oct 24 '18 17:10

user1107173


1 Answers

You can run await statement only under async function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

So, you can write your

}).then((app) => {

as

}).then(async (app) => {
like image 159
Ankush Sharma Avatar answered Oct 04 '22 07:10

Ankush Sharma