我想研究嵌套ajax请求的最佳方法或许多可能的解决方法,以使以下脚本具有专业的脚本。任何建议即兴创作。
// First request starts here
fetch(endpoint1, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email" : this.state.email,
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Second request starts here
fetch(endpoint2, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email" : this.state.email,
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Third request starts here
fetch(endpoint3, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseJson) => {
// responsejson
})
.catch((error) => {
});
// Third request ends here
})
.catch((error) => {
console.error(error);
});
// Second request ends here
})
.catch((error) => {
console.error(error);
});
// First request ends here
无论如何,这都不是问题,而只是为了理解和即兴创作。
答案 0 :(得分:0)
我认为最好将代码移至某个函数,然后在请求中重新使用它。
postApi(endpoint, params){
fetch(endpoint, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
}).then((response) => response.json())
.then((responseJson) => return responseJson )
.catch(error => return { error: true })
}
getApi(endpoint){
fetch(endpoint, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => return responseJson )
.catch(error => return { error: true })
}
calls(){
this.postApi(
endpoint1, {
"email" : this.state.email,
}).then(response1 => {
if(response1.error) {
alert("error api 1")
}else{
this.postApi(endpoint2, {
"email" : this.state.email,
}).then(response2 => {
if(response2.error){
alert("error api 2")
}else {
this.getApi(endpoint3).then(response3 => {
if(response3.error){
alert("error api 3")
}else {
// do something
}
})
}
})
}
}
)
}