我需要编写一些Javascript(ES6版本)来执行以下任务:
项目总数是可变的。所以我计划使用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()。有任何想法吗?
你可以使用递归:
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 => { ... });
也许你可以使用递归,如下所示:
//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(","));
}
});
}
在for循环中使用await
而不是then