Javascript:SyntaxError:等待仅在异步函数中有效 [英] Javascript: SyntaxError: await is only valid in async function

查看:105
本文介绍了Javascript:SyntaxError:等待仅在异步函数中有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在节点8上的 Sequelize.js

尝试使用await时出现以下错误.

Gtting the following error when trying to use 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

我在做什么错了?

推荐答案

addEventasync..await和原始承诺的混合. awaitthen的语法糖.是一个或另一个.混合会导致错误的控制流; db.App.findOne(...).then(...)承诺未链接或返回,因此无法从外部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;
}

通常,普通的回调不应与promise混合使用. callback参数表示使用addEvent的API可能也需要被传播.

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:等待仅在异步函数中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆