【发布时间】:2020-01-23 22:05:12
【问题描述】:
您好,我必须调用多个 Promise,但我被卡住了,基本上我从通过 modbus/TCP 通信的套接字服务获取数据。我能够通过一个cordova插件进行通信,但是我在理解promise的工作方式时遇到了一些问题,这里有一些代码:
ngOnInit() {
console.log('init')
this.getRegistrationNumber().then(() => {
this.swVersionRequest()
})
}
getRegistrationNumber() {
let self = this
return new Promise(function(resolve, reject) {
self.socketService.getMatricola().then((data: any) => {
self.registrationNumber = self.socketService.arrayBuffer2str(data.data.slice(3, data.data.length-2))
console.log(`Registration number is ${self.registrationNumber}`)
resolve()
})
.catch(error => {
reject(error)
})
})
}
swVersionRequest() {
console.log("software version request");
this.socketService.getSwVersion().then((data: any) => {
this.softwareVersionWifiGsm = this.socketService.arrayBuffer2str(data.data.slice(3, data.data.length-2))
this.softwareVersionWifiGsm = this.softwareVersionWifiGsm.substring(0, 2).split('').join(".") + ' ' + this.transformSwVersion(this.softwareVersionWifiGsm.substring(2, this.softwareVersionWifiGsm.length))
console.log(`Software version is ${this.softwareVersionWifiGsm}`)
})
}
getMachineType() {
console.log('get machine type')
this.socketService.getMachineType().then((data: any) => {
this.machineType = data.data.slice(4, data.data.length-2)
console.log(`Machine type is ${this.machineType}`)
})
}
refreshData() {
this.getRegistrationNumber().then(() => {
this.swVersionRequest()
})
.then(() => { // not working like this
this.getMachineType()
})
}
transformSwVersion(str: any) {
return str.replace(/(\d\d)(\d\d)(\d\d)/, "$1/$2/$3")
}
然后当我得到 machineType 时,我想检查来自 promise 的响应,可能是这样的:
if (this.machineType == 2) {
callSoftwareVersionB() // another promise
} else {
callSoftwareVersionC() // another promise
}
不知道是不是很清楚
提前谢谢你
【问题讨论】:
标签: javascript angular promise