首页 > 解决方案 > 在异步等待中使用循环提供 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)

代码的思路如下:

  1. 循环包含帐户列表的全局帐户(第一个)

  2. 准备申请欧盟地区

  3. 为我们地区准备请求

  4. 运行异步请求以获取来自欧盟的用户

  5. 循环值,如果找到 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因为我需要为欧盟和美国运行代码

标签: javascriptnode.jsperformanceasync-awaiteslint

解决方案


除非您明确想要串行循环等待的承诺,否则您应该使用Promise.allor 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
        }
    }
}

如果你真的想做一个串行循环,那么你所拥有的就可以了。


推荐阅读