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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52975133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:04:01  来源:igfitidea点击:

Javascript: SyntaxError: await is only valid in async function

javascriptnode.jsasync-awaitsequelize.jses6-promise

提问by user1107173

I am on Node 8 with Sequelize.js

我在 Node 8 上使用Sequelize.js

Gtting the following error when trying to use await.

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

SyntaxError: await is only valid in async function

SyntaxError: await is only valid in async function

Code:

代码:

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
            }
    })
}

Getting the following error:

得到以下错误:

               let result = await promise;
                            ^^^^^
               SyntaxError: await is only valid in async function

What am I doing wrong?

我究竟做错了什么?

采纳答案by Estus Flask

addEventis a mixture of async..awaitand raw promises. awaitis 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.

addEventasync..await原始承诺和原始承诺的混合体。await是 的语法糖then。它是一个或另一个。混合导致不正确的控制流;db.App.findOne(...).then(...)promise 没有被链接或返回,因此不能从外部获得addEvent

It should be:

它应该是:

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;
}

Generally plain callbacks shouldn't be mixed with promises. callbackparameter indicates that API that uses addEventmay need to be promisified as well.

通常,不应将简单的回调与承诺混合在一起。callback参数表示使用的 API 也addEvent可能需要被承诺。

回答by Ankush Sharma

You can run await statement only under async function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

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

So, you can write your

所以,你可以写你的

}).then((app) => {

as

作为

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

回答by Estus Flask

async/awaitonly works if the immediate function has the async keyword, you need this:

async/await仅当立即函数具有 async 关键字时才有效,您需要:

...
    }).then(async app => {   // <<<< here

                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
            }
    })

回答by Tibin Thomas

You can use await only inside a function which is async. Also you can await only a piece of code that returns a promise.

您只能在异步函数中使用 await。您也可以只等待一段返回承诺的代码。

Here you are using await inside a different context. Better you use then() here to solve the problem.

在这里,您在不同的上下文中使用 await。最好在这里使用 then() 来解决问题。

await only works if the immediate function that encloses it is async.

await 仅在包含它的立即函数是异步的情况下才有效。