Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  103] [ 5]  / answers: 1 / hits: 34045  / 6 Years ago, wed, october 24, 2018, 12:00:00

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?


More From » node.js

 Answers
36

addEvent is a mixture of async..await and raw promises. await is syntactic sugar for then. It's either one or another. A mixture results in incorrect control flow; db.App.findOne(...).then(...) promise is not chained or returned and thus is not available from outside addEvent.



It should be:



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

const app = await db.App.findOne({
where: {
owner_id: req.user_id,
}
});

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

let result = await promise;
}


Generally plain callbacks shouldn't be mixed with promises. callback parameter indicates that API that uses addEvent may need to be promisified as well.


[#53258] Saturday, October 20, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theo

Total Points: 680
Total Questions: 108
Total Answers: 81

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;