我遇到了一些问题,从嵌套的Promises和回调中返回数据,从我的组件中我首先调用Api方法找到checkid,当我收到checkid时,我将检查该id的状态。另一件事,当我检查状态时,我正在使用第三方服务,因此数据不会立即返回。所以我称状态api最多10次(时间超过3秒),直到我收到我的数据。 这是我的第一个实现。
deviceService使用请求库
构成简单的API方法 For Ex:
const deviceService ={
fetchID(param1){
request.get('https://.....')
}
}
//在反应组件文件中。我将API称为
API.getDeviceLockStatus(param1).then(data => {
//I need data after i reciving the value from 3rd party server
if (data) {
//DO SOMETHING
}
});
API.js文件:
var API = {
getDeviceLockStatus(param1) {
return deviceService.fetchID(param1).then(checkID => {
console.log('Got checkID here')
if (checkID) {
callStatus(checkID);
}
}, handleError);
}
}
function callStatus(checkID) {
return deviceService.fetchStatus(checkID).then(status => {
// If i receive the response from 3rd party Server i will have status.body.isAvailable = true (or False)
// if Not i will recieve status with status.checkID (this checkID is what i have supplied)
if (status.body.isAvailable) {
return status
} else {
setTimeout(callBackFunction(status.checkID), 3000)
}
},han)
}
callBackFunction(checkID) {
callStatus(checkID);
}
function handleError(){
// Error will be Handled
}
所以问题是当我调用API.getDeviceLockStatus(param1)时..它会立即返回undefined。
有人可以帮助我更好地做到这一点,或者在获取真实数据后返回实际值。
提前致谢。
答案 0 :(得分:2)
查看API.js,没有太多要改变
var API = {
getDeviceLockStatus(param1) {
return deviceService.fetchID(param1).then(checkID => {
console.log('Got checkID here')
if (checkID) {
return callStatus(checkID); // added return
}
}, handleError);
}
}
function callStatus(checkID) {
return deviceService.fetchStatus(checkID).then(status => {
// If i receive the response from 3rd party Server i will have status.body.isAvailable = true (or False)
// if Not i will recieve status with status.checkID (this checkID is what i have supplied)
if (status.body.isAvailable) {
return status
} else { // here one way to do a simple delay/retry with a Promise
return new Promise(function(resolve) {
setTimeout(resolve, 3000);
}).then(function() {
return callStatus(status.checkID);
});
}
}, handleError)
}
function handleError() {
// Error will be Handled
}