javascript - 两个函数同时执行

标签 javascript android react-native

我有一个通过蓝牙连接到两个设备的应用程序。我从这些设备中抢救了一些数据并将它们保存在数据库中。

基本上我所做的是:

搜索设备 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/

相关文章:

objective-c - 错误: @"Bridge module %@ does not conform to RCTBridgeModule"

javascript - 如何通过另一个对象访问一个对象,该对象包含一个对象,该对象是我想访问的对象的属性?

java - 如何设置 textview 中的所有行具有相同的字符长度?

javascript - 如何通过nodejs将文本转换为JSON?

java - Android媒体录制错误启动失败-19 runTimeException

java - 如何在 android 中使用 asmack 4.0.5 获取最后一次查看

react-native - react 原生 MapView : what is latitudeDelta longitudeDelta

react-native - 在外部网络上托管 Expo 应用程序?

javascript - 谷歌代码现在缺少 Crypto-JS

javascript - 如何使用 jquery 将 css 转换添加到当前转换值?