首页 > 解决方案 > Javascript: SyntaxError: await 仅在异步函数中有效

问题描述

我在使用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

我究竟做错了什么?

标签: javascriptnode.jsasync-awaitsequelize.jses6-promise

解决方案


您只能在 async 函数下运行 await 语句。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

所以,你可以写你的

}).then((app) => {

作为

}).then(async (app) => {

推荐阅读