[英]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.