Javascript: SyntaxError: await 仅在异步函数中有效

Javascript: SyntaxError: await is only valid in async function(Javascript: SyntaxError: await 仅在异步函数中有效)
本文介绍了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.

这篇关于Javascript: SyntaxError: await 仅在异步函数中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)