javascript - 我该如何解决这个错误: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}`
);
解决方案
规则一:阅读错误。
它告诉您的是,您只能在函数内部使用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
.
推荐阅读
- spring - Spring boot 2.1.13.RELEASE hatoas 链接响应与 Spring boot 1.5.14.RELEASE hateoas 链接响应不同
- ruby-on-rails - 我可以在控制台中添加数据,但是控制器中有错误
- visual-studio-code - vs-code:无法在内置终端上反向搜索
- ios - SwiftUI - 在 SwiftUI 中对 JSON 文件进行排序,分节或排序
- azure - Azure 数据工厂如何获取源计数和接收器计数以进行数据验证
- python - 创建包含英语单词的字典
- sql - 在 Redshift 中将列类型从 varchar 更改为 datestamp
- excel - 如何按数据透视表中的值字段过滤?
- reactjs - 反应日历库
- javascript - 通过 SharePoint 中的 javascript/SP 服务根据用户组成员身份在列表视图中隐藏项目行(整行)