繁体   English   中英

Javascript 使用 Vue 的同步循环内的同步循环

[英]Javascript a synchronous loop inside a synchronous loop using Vue

我有一个 JavaScript 循环

            for (var index = 0; index < this.excelData.results.length; index++) { 
            let pmidList = this.excelData.results[index]["PMIDList"];
            if (pmidList.length == 0 ){
            continue;
            }
             let count = 0;
             let pmidsList = pmidList.split(',');
              if (pmidsList.length > 200){
                pmidList = pmidsList.slice(count, count+ 200).join(',');
              } else { 
                pmidList= pmidsList.join(",");
              
               }

             // Create some type of mini loop
              // pmidList  is a comma separated string so I need to first put it into an array           
             // then slice the array into 200 item segments

               let getJSONLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?'       
               getJSONLink += 'db=pubmed&retmode=json&id=' + pmidList
               await axios.get(getJSONLink)
              .then(res => {  
                let jsonObj = res.data.result;
                   //Do Stuff with the data
                  } 
  
                }).catch(function(error) {
              console.log(error);
          });   
            //Loop
       }

除了 PMIDList 有超过 200 个逗号分隔项时,整个过程都可以正常工作。 web 服务一次只接受 200 个。 因此,我需要添加一个内部循环来解析前 20000 个并循环返回以执行 rest,然后再转到下一个索引,并且最好同步执行此操作,因为 Web 服务每秒只允许 3 个请求。 而且由于我使用的是 Vue 等待是另一个问题。

最简单的选择是在 while 循环中使用 async await,改变原始数组。 就像是:

async function doHttpStuff(params) {
    let getJSONLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?'       
    getJSONLink += 'db=pubmed&retmode=json&id=' + params.join('')
    return axios.get(getJSONLink)
}

并在你的内部 while 循环中使用它:

...
let pmidsList = pmidList.split(',');
// I'll clone this, because mutating might have some side effects?
const clone = [...pmidsList];
while(clone.length) {
  const tmp = clone.splice(0, 199); // we are mutating the array, so length is reduced
  const data = await doHttpStuff(tmp);
  // do things with data
}
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM