如何设置超时函数



我有一个问题。

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

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

如果它被卡住,它不会做任何其他事情。我想设置一个 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.")
}
});
}

据我所知,问题是device.connect()没有正确错误,所以只会静静地死去,catch将无法正常工作。

如果是这样,您可以将device.connect()包装在另一个承诺中

,并超时reject

.这个要点可以解决问题。Javascript Promise Timeout。 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.")
}
});
}

最新更新