首页 > 解决方案 > 如何设置超时功能

问题描述

我有个问题。

我有一个扫描设备的功能,如果找到设备,它将被连接。

现在我的问题是这个函数可能会因为 x 的原因而崩溃。

如果它被卡住,它不会做任何其他事情。我想设置一个 setTimeout () ,这样如果函数崩溃,一段时间后它会执行一个动作。

如何设置这个 setTimeout()?多谢!

scan1() {
    console.log(" ");
    console.log("-- Start scan device -- ");
    // IF there is error it prints only the console.log above.
    this.manager.startDeviceScan(null, null, (error, device) => {
      if (error) {
        return;
      }
      if (
        (device.name == this.model_dx(this.props.Model)) ||
        (device.name == this.model_sx(this.props.Model))
      ) {

        this.setState({ deviceId1: device.id });
        console.log("ID Device 1 (this.state.deviceId1): " + this.state.deviceId1);
        this.manager.stopDeviceScan();
        this.setState({deviceName1: device})
        console.log("(this.state.deviceName1 = device:): " + this.state.deviceName1);
        device
          .connect()
          .then(() => {
            console.log("--Connected.--");
            this.scan2();
          })
          .catch(() => {
            Alert.alert("No connection.");
            Actions.homepage();
          });
      }
      else {
        this.manager.stopDeviceScan();
        console.log("ERROR.")
      }
    });
  }

标签: javascriptreact-native

解决方案


从我收集到的问题是,device.connect()它不会正确出错,所以只会默默地死掉并且catch无法正常工作。

如果是这样,您可以device.connect()在另一个带有超时的承诺中包装到reject.

这个要点可以解决问题。Javascript 承诺超时。 https://gist.github.com/john-doherty/bcf35d39d8b30d01ae51ccdecf6c94f5

唯一的问题是您实际上无法取消device.connect(),因此在您认为它已停止之后它可能在后台做一些奇怪的事情,或者它可能是重试的问题。最好的办法是检查一下device.connect(),看看你是否可以向它传递一个实际上可以拒绝承诺的回调。如果你不能,这应该工作。

function promiseTimeout(ms, promise){

  return new Promise(function(resolve, reject){

    // create a timeout to reject promise if not resolved
    var timer = setTimeout(function(){
        reject(
            // Do whatever you want here after the timeout            
        );
    }, ms);

    promise
        .then(function(res){
            clearTimeout(timer);
            resolve(res);
        })
        .catch(function(err){
            clearTimeout(timer);
            reject(err);
        });
  });
};

scan1() {
    console.log(" ");
    console.log("-- Start scan device -- ");
    // IF there is error it prints only the console.log above.
    this.manager.startDeviceScan(null, null, (error, device) => {
      if (error) {
        return;
      }
      if (
        (device.name == this.model_dx(this.props.Model)) ||
        (device.name == this.model_sx(this.props.Model))
      ) {

        this.setState({ deviceId1: device.id });
        console.log("ID Device 1 (this.state.deviceId1): " + this.state.deviceId1);
        this.manager.stopDeviceScan();
        this.setState({deviceName1: device})
        console.log("(this.state.deviceName1 = device:): " + this.state.deviceName1);

promiseTimeout(device.connect(), 500)
  .then(() => {
    console.log("--Connected.--");
    this.scan2();
  })
  .catch(() => {
    Alert.alert("No connection.");
    Actions.homepage();
  });
}
      else {
        this.manager.stopDeviceScan();
        console.log("ERROR.")
      }
    });
  }

推荐阅读