ES6使用异步调用进行循环

问题描述 投票:0回答:3

我需要编写一些Javascript(ES6版本)来执行以下任务:

  1. 字符串是“item1,item2,item3,item4,item5”,
  2. 使用此字符串fetch()一个URL。
  3. 如果响应标志成功,则完成并退出。
  4. 如果响应标志是失败,则删除最后一项(item5),所以现在字符串是“item1,item2,item3,item4”并重复步骤2。
  5. 如果没有更多项目要删除,请退出。

项目总数是可变的。所以我计划使用do-loop执行此任务,使用以下结构:

//suppose str = 'item1,item2,item3,....itemN'
do {
    fetch(url, {param1: str}).then(response => {
        //check the response flag, if success, done and exit.
        //if not success, drop one item and re-do fetch
    })
}

问题是fetch是一个异步调用,所以我不能强制执行序列中执行的每次提取。

我需要确保只在前一个fetch()失败时才执行新的fetch()。有任何想法吗?

javascript ecmascript-6 es6-promise
3个回答
2
投票

你可以使用递归:

function fetchRecursive(param) {

  return fetch(url, {param1: param})
    .then(response => response.ok ? response : Promise.reject(new Error(response.status)))
    .catch((err) => {
      if (param.length > 1) {
        return fetchRecursive(param.slice(0,-1));
      } else {
        return Promise.reject(err);
      }
    })
}

fetchRecursive([ 'item1', 'item2', 'item3', 'item4' ])
  .then(response => { ... })
  .catch(err => { ... });

0
投票

也许你可以使用递归,如下所示:

//str = 'item1,item2,item3,....itemN'
function fetchUrl(str){
  fetch(url, {param1: str}).then(response => {
        if(response.success){
          //exit from the program
          return response;
        }
        else
        {
          return fetchUrl(str.split(",").pop().join(","));
        }
    });
}

-2
投票

在for循环中使用await而不是then

© www.soinside.com 2019 - 2024. All rights reserved.