Javascript: SyntaxError: await is only valid in async function(Javascript: SyntaxError: await 仅在异步函数中有效)
问题描述
我在 Node 8 上使用 Sequelize.js
I am on Node 8 with Sequelize.js
尝试使用 await 时出现以下错误.
Gtting the following error when trying to use await.
SyntaxError: await 仅在异步函数中有效
代码:
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 和原始 promise 的混合体.await 是 then 的语法糖.它是一个或另一个.混合导致不正确的控制流;db.App.findOne(...).then(...) promise 没有被链接或返回,因此在 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;
}
一般来说,简单的回调不应与承诺混合.callback 参数表示使用addEvent 的API 可能也需要promisified.
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: await 仅在异步函数中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript: SyntaxError: await 仅在异步函数中有效
基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
