Javascript:SyntaxError:等待仅在异步函数中有效 [英] Javascript: SyntaxError: await is only valid in async function
问题描述
我在节点8上的 Sequelize.js
尝试使用await
时出现以下错误.
Gtting the following error when trying to use await
.
SyntaxError: await is only valid in async function
代码:
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
}
})
}
出现以下错误:
let result = await promise;
^^^^^
SyntaxError: await is only valid in async function
我在做什么错了?
推荐答案
addEvent
是async..await
和原始承诺的混合. await
是then
的语法糖.是一个或另一个.混合会导致错误的控制流; db.App.findOne(...).then(...)
承诺未链接或返回,因此无法从外部addEvent
获得.
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
.
应该是:
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;
}
通常,普通的回调不应与promise混合使用. callback
参数表示使用addEvent
的API可能也需要被传播.
Generally plain callbacks shouldn't be mixed with promises. callback
parameter indicates that API that uses addEvent
may need to be promisified as well.
这篇关于Javascript:SyntaxError:等待仅在异步函数中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!