javascript - Javascript: SyntaxError: await 仅在异步函数中有效
问题描述
尝试使用时出现以下错误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
我究竟做错了什么?
解决方案
您只能在 async 函数下运行 await 语句。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
所以,你可以写你的
}).then((app) => {
作为
}).then(async (app) => {
推荐阅读
- reactjs - 使用 Firebase 存储 + useEffect hook + useState hook 渲染图像时遇到问题
- http - 如何使用 HTTP.jl 获取客户端 IP 地址
- javascript - “d3.select(...) 不是函数”
- python - (Flask)如何在 html 中创建一个 If 语句来检测 for 循环中的最后一项
- ios - 开发依赖于原生框架的 react-native 库
- javascript - 同步 XMLHttpRequest 问题
- python - 过滤 Tweepy 流的问题
- c++ - 使用 clang CMake 包含 Boost 构建
- java - 如果假设一个接口是完全抽象的,为什么这段代码可以工作?
- vba - 为什么无法访问公共网站?