我正在使用访存来从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());
}
然后我称之为:
async componentDidMount() {
let response = await this._getDcnDetail(dcn.DcnId);
console.log(response);
}
但是它“永恒地”等待着,它没有兑现承诺。
据我了解,fetch返回了一个promise,它会由response.json()解析。我用“等待”来等待诺言得到解决,所以不确定什么是错的。
答案 0 :(得分:0)
首先检查您的POST请求是否发生了一些错误
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"));
}
此外,您应该将其重构为
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;
}
}