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

我做错了什么?

推荐答案

addEventasync..await 和原始 promise 的混合体.awaitthen 的语法糖.它是一个或另一个.混合导致不正确的控制流;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.

相关文章