我在Sequelize.js上的Node 8上
尝试使用时出现以下错误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
。
它应该是:
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
参数指示使用的APIaddEvent
可能也需要被告知。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句