首页 > 解决方案 > 我该如何解决这个错误:SyntaxError: await is only valid in async function

问题描述

我正在尝试创建一个不和谐的机器人来显示有关加密货币的一些信息,并且出现以下错误 SyntaxError: await is only valid in async function,这部分代码让我遇到了问题:

 const [coin, vsCurrency] = args;
      try {
        const { data } = await axios.get(
        `https://api.coingecko.com/api/v3/simple/price?ids=${coin}&vs_currencies=${vsCurrency}`
        );

标签: javascriptnode.js

解决方案


规则一:阅读错误

它告诉您的是,您只能在函数内部使用await关键字。所以你的一段代码必须像这样包装:async

async function run() {

 const [coin, vsCurrency] = args;
 try {
   const { data } = await axios.get(`https://api.coingecko.com/api/v3/simple/priceids=${coin}&vs_currencies=${vsCurrency}`);
 } catch (err) {
   // Do something about the error.
 }
}

// Don't forget to run your function
run();

阅读本文以更好地理解async/await.


推荐阅读