两个函数同时执行

时间:2019-09-11 08:08:59

标签: 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);
            });
        }
      }

2 个答案:

答案 0 :(得分:3)

因为promise是异步的,所以您必须嵌套第二个函数我的朋友,或者:您可以使一个异步函数包装对这两个函数的调用并使用“ await”。不知道该怎么办。

答案 1 :(得分:1)

每当您发现自己使用数字作为方法名称的后缀时,这是一个很好的指示,您可以进行迭代。虽然重复自己并不总是很糟糕,但是您的代码是多余的。 另外,通过立即停止对每个设备的扫描,很有可能第一个设备将被简单地扫描并连接两次。

startDeviceScan回调称为once per device.,所以我们只需要调用一次,直到两个设备连接,然后然后停止扫描。

Promise.all兑现了一系列承诺,使我们能够同时设置两个设备,从而消除了用户体验的延迟。

您会发现我经常使用async/await。这只是风格和习惯的问题。如果没有此代码,也可以实现。

async scanDevices() {
    const bothDevices = await new Promise((resolve, reject) => {
        // Timeout failsafe if devices never connect
        setTimeout(
            () => reject(new Error('Device scan timed out')),
            10000 /* 10 seconds */
        );
        const devices = [];
        this.manager.startDeviceScan(
            null,
            null,
            /* Listener Called For Every Device */
            async (error, device) => {
                // exit on error
                if (error) return console.error(error);
                try {
                    // exit callback if already connected 
                    if (await device.isConnected()) return;
                    // connect
                    await device.connect();
                    console.log(`DEVICE: ${device.name} - CONNECTED`);
                    devices.push(device);
                    // Only scan 2 devices
                    if (devices.length >= 2) {
                        this.manager.stopDeviceScan();
                        // resolves promise, setting `bothDevices` 
                        resolve(devices);
                    }
                } catch (e) {
                    console.error(e);
                }
            }
        );
    });
    // Setup both at the same time
    await Promise.all(bothDevices.map(device => this.setupDevice(device)));
}

async setupDevice(device) {
    try {
        await device.discoverAllServicesAndCharacteristics();
        this.setupNotifications(device);
    } catch (e) {
        this.error(e.message);
    }
}