【发布时间】:2020-09-06 16:05:20
【问题描述】:
我必须一个接一个地执行三个获取请求。这意味着,假设我的三个 fetch 请求是:
const A = (url) => (dispatch) => {
let req = fetch(url, ....)
.then(response => {
if (!response.ok) {
throw response;
}
return response.json();
}).then(response => {
}).catch(error => {
})
}
const B = (url) => (dispatch) => {
let req = fetch(url, ....)
.then(response => {
if (!response.ok) {
throw response;
}
return response.json();
}).then(response => {
}).catch(error => {
})
}
const C= (url) => (dispatch) => {
let req = fetch(url, ....)
.then(response => {
if (!response.ok) {
throw response;
}
return response.json();
}).then(response => {
}).catch(error => {
})
}
首先“A”应该被执行,然后B应该在A完成时执行,然后C应该在B完成时执行。一旦A,B,C完成,我想执行一个函数
doSomething = () => {
//do something after A, B, C are executed
}
我对“承诺”很陌生。有人可以指导我如何做到这一点吗?
以下是我尝试过的实际代码
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 => {
})
}
在上面的代码中,只有第一个 fecth ("DELETE") 被执行。随后的提取不会被执行。
【问题讨论】:
-
A().then(() => B()).then(() => C).then(doSomething)? -
这行不通。
-
然后提供minimal reproducible example 说明您尝试过的方法以及问题所在。
-
当然。我已经在更新中附加了实现的代码。请看一看。
-
注意“最小”。而你说“不起作用” - 那么会发生什么?
标签: javascript promise fetch es6-promise