Javascript 带异步调用的ES6循环
我需要编写一些Javascript(ES6版本)来执行以下任务:Javascript 带异步调用的ES6循环,javascript,ecmascript-6,es6-promise,Javascript,Ecmascript 6,Es6 Promise,我需要编写一些Javascript(ES6版本)来执行以下任务: 字符串是“item1,item2,item3,item4,item5” fetch()使用此字符串获取URL 如果响应标志为成功,则完成并退出 如果响应标志为失败,则删除最后一项(item5),因此现在字符串为“item1、item2、item3、item4”,并重复步骤2 如果没有更多要放下的项目,请退出 项目总数是可变的。因此,我计划使用do循环执行此任务,使用以下结构: //suppose str = 'item1,item
//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()只在前一个fetch()失败时执行。有什么想法吗?用
wait
代替,然后在for循环中使用可能你可以使用递归,类似这样:
//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(","));
}
});
}
您可以使用递归:
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 => { ... });
function doFetch(){if(arr.length>0)fetch(url,{param1:arr.pop()})。然后(response=>{if(!success)doFetch();})可以使用ES8吗?(使用HTML5fetch
API而不是一些任意的fetch
函数,它需要是fetch(…)。然后(response=>response.ok?response.json()):Promise.reject(新错误(response.status))).catch(…)
左右,但泛型方法为+1)你是对的。另外,我的代码也不完全正确。修复了它。对它们之间的差异以及它的重要性多做一点解释会很有帮助!