已添加async修饰仍报SyntaxError: await is only valid in async function如何解决
错误原因
你仅给外层run函数添加了async修饰,但await实际是在forEach的回调函数作用域内执行,该回调并未被async修饰,因此触发语法报错。
修复方案
方案1:使用for...of循环(推荐,顺序执行)
直接替换forEach为for...of,不需要额外声明其他异步函数,可保证按附件顺序依次执行请求:
const fetch = require("node-fetch") module.exports = { name: "find", aliases: ["f"], run: async (message) => { for (const attachment of message.attachments) { const url = attachment.url; console.log(url); const res1 = await fetch( `https://saucenao.com/search.php?db=999&output_type=2&testmode=1&numres=16&url=${url}` ); const data1 = await res1.json(); console.log(data1); } }, };
方案2:并行执行请求(适合高并发场景)
如果不需要按顺序执行,可通过map收集所有异步任务,再用Promise.all统一等待所有请求完成:
const fetch = require("node-fetch") module.exports = { name: "find", aliases: ["f"], run: async (message) => { const tasks = message.attachments.map(async (attachment) => { const url = attachment.url; console.log(url); const res1 = await fetch( `https://saucenao.com/search.php?db=999&output_type=2&testmode=1&numres=16&url=${url}` ); const data1 = await res1.json(); console.log(data1); }); await Promise.all(tasks); }, };
注意点
- 不要直接给
forEach的回调加async,这种写法无法让外层run函数等待所有异步请求执行完毕,会出现逻辑提前终止的问题 - 单条请求出错会中断
Promise.all的执行,需要做异常捕获可自行给每个异步任务加try/catch包裹
内容的提问来源于stack exchange,提问作者one ppment
相关产品推荐
相关产品推荐

