问题
I'm working on a project where a want to use web bluetooth to connect to a BLE device. I looked trough multiple tutorials and tried to make those work. In the code below i get the characteristic of the device. The code works but I don't know why.
I want my promise to activate when a device is found and connected to. But when I put the connect .then in the promise the other .then already activates when I launch the application.
function read() {
let prom = new Promise(function (resolve, reject) {
navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: []
})
.then((device) => {
console.log('Discovered', device);
PCB= device;
resolve();
return PCB.gatt.connect();
})
.then(server => {
gattServer = server;
console.log('getting server');
return gattServer.getPrimaryService(0x1815);
})
.then(service => {
console.log('getting characteristic');
if(0x2a56){
return service.getCharacteristic(0x2a56);
}
return service.getCharacteristic();
})
.then(characteristics => {
console.log('> Characteristics: ' + characteristics + characteristics.map(c => c.uuid).join('\n' + ' '.repeat(19)));
})
.catch(error => {
console.log(error);
reject();
});
})
}
回答1:
You need to
- Return your promise from your function.
- Resolve your promise when the sequence of operations complete.
Your question example, modified with //1, and //2.
function read() {
return new Promise(function(resolve, reject) { // 1
navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: []
})
.then((device) => {
console.log('Discovered', device);
PCB = device;
resolve();
return PCB.gatt.connect();
})
.then(server => {
gattServer = server;
console.log('getting server');
return gattServer.getPrimaryService(0x1815);
})
.then(service => {
console.log('getting characteristic');
if (0x2a56) {
return service.getCharacteristic(0x2a56);
}
return service.getCharacteristic();
})
.then(characteristics => {
console.log('> Characteristics: ' + characteristics +
characteristics.map(c => c.uuid).join('\n' + ' '.repeat(19)));
resolve(); // 2
})
.catch(error => {
console.log(error);
reject();
});
})
}
来源:https://stackoverflow.com/questions/57968195/web-bluetooth-with-promises