javascript - 在异步等待中使用循环提供 eslint 错误
问题描述
我有以下代码有效,我目前配置 eslint 并得到以下错误
1. ESLint: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. (no-restricted-syntax)
2. ESLint: Unexpected `await` inside a loop. (no-await-in-loop)
代码的思路如下:
循环包含帐户列表的全局帐户(第一个)
准备申请欧盟地区
为我们地区准备请求
运行异步请求以获取来自欧盟的用户
循环值,如果找到 url 返回 6 - 7 与 4-5 相同,但适用于美国地区
async function acount(global) { // here i got the first eslint error iterators/generators for (const account of global) { // create http request for getting the users - region EU let usersEUReq = getUsers(account.guid, region.1); // create http request for getting the users region US let usersUSReq = getUsers(account.guid, region.2); const usersEU = await axios(usersEUReq); // here I got the response from the promise and should loop on it got get URL for (const sub of usersEU.data) { if (sub.url) { return sub.url } } const usersUS = await axios(usersUSBReq); for (const sub of usersUS.sub) { if (sub.url) { return sub.url } } }
顺便说一句,我不能使用Promise.all
或者race
因为我需要为欧盟和美国运行代码
解决方案
除非您明确想要串行循环等待的承诺,否则您应该使用Promise.all
or Promise.race
(或者Promise.any()
当所有主要浏览器都支持它时)。他们将同时履行你的承诺。
例如:
function getuserdata(account) {
return [region.1, region.2].map(_region => getUsers(account.guid, _region)).map(axios);
}
async function acount(global) {
let userdata = await Promise.all(global.flatMap(getuserdata))
for (const sub of userdata) {
if (sub.url) {
return sub.url
}
}
}
如果你真的想做一个串行循环,那么你所拥有的就可以了。
推荐阅读
- python - 从 url python 检索文件
- amazon-web-services - AWS Autoscaling on CloudWatch SQS 指标问题
- azure - 使用 powershell 获取 Azure Web/Function App 身份验证配置
- javascript - 禁用 div 或 html 页面的所有动画
- regex - 是否可以在插值的正则表达式中进行捕获?
- wso2 - 将参数作为环境变量注入时出现 WSO2 端点部署错误
- python - tensorflow正确导入图像
- amazon-web-services - AWS SES - 卡在域验证上
- html - “下一个”的按键事件
- javascript - 水平导航栏悬停效果jquery