我正在使用 Angular 开发 Ionic v4 项目。
在我的项目中,我使用 BLE 与树莓派通信。
我需要完成以下几个步骤:
- 搜索设备
- 连接设备
- 启用通知
- 发送消息
目前我的实现大致如下:
this.ble.scan().subscribe(result => {
if (device === theDeviceIWant) {
this.ble.connect(device.id).subscribe(result => {
this.ble.startNotification(infosaboutDevice).subscribe(result => {
// Message 1
this.ble.writeWithoutResponse(infos, message).then(result => {
// Message 2
this.ble.writeWithoutResponse(infos, message).then(result => {
// Message 3
this.ble.writeWithoutResponse(infos, message).then(result => {
// Message X
this.ble.writeWithoutResponse(infos, message).then(result => {
})
})
})
})
})
})
})
}
我想做类似这样的事情:
this.myScan();
this.myConnect();
this.myNotification();
this.myMessage('Text 1');
this.myMessage('Text 2');
this.myMessage('Text X');
问题: 我的函数 'myConnect' 在等待 'myScan' 结束后才开始执行。 因此,一些 'myConnect' 需要的东西在 'myScan' 中完成。 我已经尝试使用 'async/await' 但没有起作用。 我认为我没有正确使用它:
await this.myConnect().then(async () => {
await this.myNotification().then(async () => {
await this.myMessage('03020000').then(async () => {
await this.myMessage('010100').then(async () => {
await this.myMessage('020200' + this.random.toString(16));
});
});
});
});
帮我理解如何创建一个函数,它可以等待前一个结束后再开始 :D