[英]Function returning before the result from a promise?
getShowPopup(fileName,zoneId) {
return this.getDataFromServer(fileName,zoneId).then((response) => {
return response;
});
}
const showPopup = this.Service.getShowPopup(fileName,this.id);
showPopup 被分配了一个未定义的值。 在调试时,getShowPopup 方法在 promise 执行之前返回值。 我怎样才能使这个同步,以便它等待响应,然后返回正确的结果。
我认为更好的方法是让它像这样:
// it should return Promise
function getShowPopup(fileName,zoneId) {
return this.getDataFromServer(fileName,zoneId);
}
// and then when you want to get value from this api call
const showPopup = this.Service.getShowPopup(fileName,this.id)
.then(response => response)
.catch(error => console.log(error));
现在 showPopup const 应该有价值。 其他方法是使 function 异步
async function getShowPopup(fileName,zoneId) {
return this.getDataFromServer(fileName,zoneId);
}
然后你只需要使用关键字等待
// but if api call returns error, it will not be caught so you should put this call in try catch block
const showPopup = await this.Service.getShowPopup(fileName, this.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.