Reputation: 2113
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?
Upvotes: 0
Views: 90
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
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