我有一个通过蓝牙连接到两个设备的应用程序。我从这些设备中抢救了一些数据并将它们保存在数据库中。
基本上我所做的是:
搜索设备 1 并连接,在此函数中我启动搜索设备 2
搜索设备 2 并连接,在此函数中,我首先启动一个函数来从设备 1 恢复服务(我需要从外部设备恢复的数据),然后从设备 2 恢复服务。
这样当我恢复数据时,两个设备就会有延迟。因此,连接的第一个设备比第二个设备先发送数据。
您认为,我该如何优化这段代码,以使两个设备收集的数据不存在这种差异?
这是我的代码:
scan1() { // scan to find the first device.
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
return;
}
this.manager.stopDeviceScan();
device
.connect()
.then(() => {
// launch function to find the second device.
this.scan2();
}
// Function to find the second device.
scan2() {
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
return;
}
this.manager.stopDeviceScan();
device
.connect()
.then(() => {
console.log("--Connected.--");
console.log(" ");
})
.then(() => {
// function to find services from device1
this.deviceService1(this.state.deviceName1);
// function to find services from device2
this.deviceService2(this.state.deviceName2);
})
deviceService1(device) {
console.log("device.name: " + device.name)
device
.discoverAllServicesAndCharacteristics()
.then(() => {
console.log("(this.setupNotifications1") // This is the function about the type of data that I need to recover
this.setupNotifications1(device);
})
.catch(error => {
this.error(error.message);
});
}
}
deviceService2(device) {
console.log("device.name: " + device.name)
device
.discoverAllServicesAndCharacteristics()
.then(() => {
console.log("(this.setupNotifications2") // This is the function about the type of data that I need to recover
this.setupNotifications2(device);
})
.catch(error => {
this.error(error.message);
});
}
}
最佳答案
因为 Promise 是异步的,所以你必须嵌套第二个函数,我的 friend ,或者:你可以让一个异步函数包装对这两个函数的调用并使用“await”。不知道还有什么办法可以解决这个问题。
关于javascript - 两个函数同时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57884793/