use*_*173 4 javascript node.js async-await sequelize.js es6-promise
我在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
}
})
}
Run Code Online (Sandbox Code Playgroud)
出现以下错误:
let result = await promise;
^^^^^
SyntaxError: await is only valid in async function
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
小智 7
您只能在异步功能下运行await语句。 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
所以,你可以写你的
}).then((app) => {
Run Code Online (Sandbox Code Playgroud)
如
}).then(async (app) => {
Run Code Online (Sandbox Code Playgroud)
addEvent是async..await原始承诺和原始承诺的混合体。await是 的语法糖then。它是一个或另一个。混合导致不正确的控制流;db.App.findOne(...).then(...)promise 没有被链接或返回,因此不能从外部获得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;
}
Run Code Online (Sandbox Code Playgroud)
通常,不应将简单的回调与承诺混合在一起。callback参数表示使用的 API 也addEvent可能需要被承诺。
| 归档时间: |
|
| 查看次数: |
8328 次 |
| 最近记录: |