Javascript 在fetch内部使用fetch并不是执行所有的fetch请求
我正在尝试一个接一个地执行三个获取请求。每个提取请求应在前一个提取请求完成时触发。下面是我的代码Javascript 在fetch内部使用fetch并不是执行所有的fetch请求,javascript,promise,fetch,Javascript,Promise,Fetch,我正在尝试一个接一个地执行三个获取请求。每个提取请求应在前一个提取请求完成时触发。下面是我的代码 const chopSegment = (token, frame_tag_url, tag_to_delete_id, chopped_tag_array, tags_for_index_update) => (dispatch) => { let req = fetch(frame_tag_url + tag_to_delete_id + "/", {
const chopSegment = (token, frame_tag_url, tag_to_delete_id, chopped_tag_array, tags_for_index_update) => (dispatch) => {
let req = fetch(frame_tag_url + tag_to_delete_id + "/",
{
method: "DELETE",
headers: {
"Authorization": "Token " + token,
"content-type": "application/json"
}
})
req.then(response => {
if (!response.ok) {
throw response;
}
else
return response.json();
}).then(response => {
return fetch(frame_tag_url,
{
method: "POST",
headers: {
"Authorization": "Token " + token,
"content-type": "application/json",
},
body : JSON.stringify(tags_for_index_update)
}).then(response1 => {
if (!response1.ok) {
throw response1;
}
return response1.json();
}).then(response => {
for(let i = 0; i < chopped_tag_array.length; i++){
return fetch(frame_tag_url,
{
method: "POST",
body: JSON.stringify(chopped_tag_array[i]),
headers: {
"Authorization": "Token " + token,
"content-type": "application/json"
}
})
.then(response2 => {
if (!response2.ok) {
throw response2;
}
return response2.json();
}).then(response2 => {
dispatch(chopSegmentSuccess(response2))
}).catch(error => {
})
}
}).catch(error => {
})
}).catch(error => {
})
}
const-chopegment=(令牌、帧标记url、标记删除id、切碎标记数组、标记更新)=>(调度)=>{
let req=fetch(frame_tag_url+tag_to_delete_id+“/”,
{
方法:“删除”,
标题:{
“授权”:“令牌”+令牌,
“内容类型”:“应用程序/json”
}
})
然后请求(响应=>{
如果(!response.ok){
投掷反应;
}
其他的
返回response.json();
})。然后(响应=>{
返回获取(帧标记url,
{
方法:“张贴”,
标题:{
“授权”:“令牌”+令牌,
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify(标签用于索引更新)
})。然后(响应1=>{
如果(!response1.ok){
抛出响应1;
}
返回response1.json();
})。然后(响应=>{
for(设i=0;i{
如果(!response2.ok){
投掷反应2;
}
返回response2.json();
}).然后(响应2=>{
调度(印章段成功(响应2))
}).catch(错误=>{
})
}
}).catch(错误=>{
})
}).catch(错误=>{
})
}
在我的代码中,只执行第一次获取,即“DELETE”?我做错了什么?你不能在循环中进行抓取。您将返回完成的第一次获取。使用promissions或wait/async来获取循环。
我宁愿这样做,创建一个iLife并递归调用它,用于后续的获取请求:
return dispatch =>{
var ctr = 0;
(function myFunc(url, headerObj){
fetch(url, headerObj)
.then(response => {
response.json().then(data=>{
ctr++;
if(ctr ===1 ){ // This could be any condition, say, something on the basis of response; I have taken `ctr` as a condition
myFunc(url, { //You may change this even to different URL, if needed
method: 'POST',
headers: {
'content-type': 'application/json',
'body': ...,
'Authorization':...
}
});
}else if(ctr === 2){
myFunc(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'body': ...,
'Authorization':...
}
});
}else{
// Any other code
}
})
})
})(url, headerObj);
}
有一件事很明显,那就是您正在捕获错误,但随后继续忽略它们。
catch()
的要点是处理错误。我建议删除fetch关键字的return,然后重试。