简体   繁体   English

如何解决:SyntaxError: await is only valid in async function

[英]How to resolve: SyntaxError: await is only valid in async function

else if(command=='quote')
  {
    let getQuote=async() => 
    {
      let result= await fetch('<api>')
      let json = await result.json()
      return json
    }
    let quote = await getQuote()
    message.channel.send(quote);
  }

I am getting error at let quote = await getQuote() as我在let quote = await getQuote() as 时遇到错误

SyntaxError: await is only valid in async function SyntaxError: await 仅在异步中有效 function

How to solve this?如何解决这个问题?

Think about the scope.想想 scope。 Your second "await" is out of the scope of the async function.您的第二个“等待”不在异步 function 的 scope 之外。 I mean following code part should put in the scope of the async function.我的意思是下面的代码部分应该放在异步 function 的 scope 中。

 let quote = await getQuote() message.channel.send(quote);

You can wrapper the code with IIFE,so in your example您可以使用 IIFE 包装代码,因此在您的示例中

else if(command=='quote')
  {
(async() => {
    let getQuote=async() => 
    {
      let result= await fetch('<api>')
      let json = await result.json()
      return json
    }
    let quote = await getQuote()
    message.channel.send(quote);
    })()
  }

or I recommended或者我推荐

else if(command=='quote')
  {
    let getQuote=async() => 
    {
      let result= await fetch('<api>')
      let json = await result.json()
      return json
    }

    getQuote().then(quote=>{message.channel.send(quote)});
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript:SyntaxError:await仅在异步函数中有效 - Javascript: SyntaxError: await is only valid in async function 未捕获的SyntaxError:await仅在异步函数的异步函数中有效 - Uncaught SyntaxError: await is only valid in async function in async function 如何解决语法错误:await 仅在异步函数中有效? - How to resolve the Syntax error : await is only valid in async function? JS await 仅在异步函数中有效。 如何解决? - JS await only valid in async function. How to resolve? SyntaxError: await 仅在异步中有效 function **而且我有异步** - SyntaxError: await is only valid in async function **and I have async** SyntaxError: await 仅在异步中有效 function 我如何使用异步? - SyntaxError: await is only valid in async function how can i use async? SyntaxError: await 仅在 async 函数中有效。 无法纠正 - SyntaxError: await is only valid in async function. Unable to Correct it Appium 代码生成“SyntaxError: await is only valid in async function” - Appium code generates "SyntaxError: await is only valid in async function" Node Js - SyntaxError: await 仅在异步中有效 function - Node Js - SyntaxError: await is only valid in async function SyntaxError: await 仅在我的代码中的异步 function 中有效 - SyntaxError: await is only valid in async function in my code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM