问题
I am using fetch to read data from a API:
async _getDcnDetail(dcnId) {
return await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
}).then(response => response.json());
}
Then I call it:
async componentDidMount() {
let response = await this._getDcnDetail(dcn.DcnId);
console.log(response);
}
But it "waits" eternally, it is not resolving the promise.
As I understand fetch returns a promise which gets resolved by response.json(). I use "await" to wait the promise to be resolved, so not sure, what is wrong.
回答1:
First of all check if some error occured on your POST request
async _getDcnDetail(dcnId) {
return await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
}).then(response => response.json())
.catch(err => alert("maybe some error occured"));
}
Additionally, you should refactor this as,
async _getDcnDetail(dcnId) {
try{
const response = await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
});
response = response.json();
return response;
} catch(e){
console.log("error", e);
throw err;
}
}
Do have a look on promises and async/await
来源:https://stackoverflow.com/questions/57661630/fetch-call-freezes