LazNiko
LazNiko

Reputation: 2113

ES6 looping with async call

I need to write some Javascript (ES6 version) to perform the following task:

  1. the string is "item1,item2,item3,item4,item5",
  2. fetch() an URL using this string.
  3. if the response flag is a success, done and exit.
  4. if the response flag is a fail, drop the last item (item5) so now the string is "item1,item2,item3,item4" and repeat step 2.
  5. if no more item to drop, exit.

The total number of items is variable. So I plan to perform this task using a do-loop, using the following structure:

//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
    })
}

The problem is that the fetch is an async call so I cannot force each fetch executed in a sequence.

I need to make sure a new fetch() only executed when the previous fetch() fail. Any ideas?

Upvotes: 0

Views: 90

Answers (3)

Josh
Josh

Reputation: 669

You could use recursion:

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 => { ... });

Upvotes: 2

Avinash
Avinash

Reputation: 2185

May be you can use recurrsion, something like this:

//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(","));
        }
    });
}

Upvotes: 0

Matt
Matt

Reputation: 2290

use await instead of then in a for loop

Upvotes: -1

Related Questions