我正在编写一个使用蓝牙模块的React-native应用程序。我的目标是使扫描/连接/发现功能异步,以便我可以等待它并相应地管理返回值。
这是我现在拥有的代码:
async writeData(data) {
this.store.dispatch({type: "START_LOADER"})
await this.manager.isDeviceConnected(this.deviceId).then(res => {
if (res) {
const device = this.store.getState().store.device
device.writeCharacteristicWithoutResponseForService(
data.serviceId,
data.charId,
data.dataToWrite
).then(res => {
this.store.dispatch({type: "SET_STATUS", payload: `${data.message}!\n`})
this.store.dispatch({type: "STOP_LOADER"})
}).catch(error => {
this.store.dispatch({type: "SET_ERROR", payload: error.message})
this.store.dispatch({type: "STOP_LOADER"})
})
return true
} else {
const timeout = setTimeout(() => {
this.store.dispatch({type: "STOP_LOADER"})
this.store.dispatch({type: "SET_ERROR", payload: 'Function timeout: device not found'})
return
}, 10000)
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
this.store.dispatch({type: "SET_ERROR", payload: error.message})
return
}
if (device.id === this.deviceId) {
clearTimeout(timeout)
this.store.dispatch({type: "SET_STATUS", payload: "North Sense found, stopping device scan...\n"})
this.store.dispatch({type: "SET_DEVICE", payload: device})
this.manager.stopDeviceScan();
device.connect().then((device) => {
this.store.dispatch({type: "SET_STATUS", payload: "device is connected!\n"})
return device.discoverAllServicesAndCharacteristics()
}).then((device) => {
device.writeCharacteristicWithoutResponseForService(
data.serviceId,
data.charId,
data.dataToWrite
).then(res => {
this.store.dispatch({type: "SET_STATUS", payload: `${data.message}!\n`})
this.store.dispatch({type: "STOP_LOADER"})
}).catch(error => {
this.store.dispatch({type: "SET_ERROR", payload: error.message})
this.store.dispatch({type: "STOP_LOADER"})
})
}).catch((error) => {
this.store.dispatch({type: "SET_ERROR", payload: error.message})
this.store.dispatch({type: "STOP_LOADER"})
});
}
});
}
}).catch(error => {
this.store.dispatch({type: "SET_ERROR", payload: error.message})
return error
})
}
此代码被插入到类的上下文中,因此,我使用此函数的方式如下:
const blApi = new blApi(deviceId)
console.log('1')
blApi.writeData({
serviceId: Config.SERVICE_ID,
charId: Config.ADD_PROGRAM_CHAR_ID,
dataToWrite: btoa(`4;${this.state.bearing};${Config.SENSING_LOCATION_INDEX}`),
message: "Person has been successfully added.",
})
console.log('2')
日志不等待函数返回,特别是在触发超时的情况下(如果蓝牙设备不在身边)并且超时在10秒后到期,我希望函数等待那10个继续下一行之前的秒数。
我该如何解决?