Я пишу родное приложение, которое использует модуль Bluetooth. Моя цель - сделать функцию сканирования / подключения / обнаружения асинхронной, чтобы я мог подождать ее и соответствующим образом обработать возвращаемое значение.
Это код, который у меня сейчас есть:
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')
Журналы не ждут возврата функции, особенно когда случайтайм-аут срабатывает (в случае, если устройство bluetooth отсутствует) и время ожидания истекает через 10 секунд. Я ожидаю, что функция подождет эти 10 секунд, прежде чем перейти к следующей строке.
Как это исправить?