Search code examples
javascriptecmascript-6es6-promise

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?


Solution

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