I need to write some Javascript (ES6 version) to perform the following task:
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?
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 => { ... });