I am writing an Angular2 based mobile app, using Typescript with the Nativescript runtime, but am facing some issues with Promises. I have a HomeComponent, from which I would like to be able to call various Bluetooth functions. These require human interaction (like selecting the device) and wait periods for the Bluetooth scan, so they take several seconds to complete.
I want to abstract those methods as promises, so I have done this:
HomeComponent.ts:
bluetoothAdd() {
this.isScanning = true;
this._ble.scan().then(
// Log the fulfillment value
function (val) {
this.isScanning = false; //hide activity indicator
this.Connect(this.ble._peripheral);
})
.catch(
function (reason) {
this.isScanning = false; //hide activity indicator
console.log('Handle rejected promise (' + reason + ') here.');
});
}
BluetoothUtils.ts (this is imported above as this._ble):
var devices: Array<string>;
var _peripheral: any;
export function scan() {
return new Promise((resolve, reject) => {
bluetooth.hasCoarseLocationPermission().then(
(granted) => {
if (!granted) {
bluetooth.requestCoarseLocationPermission();
} else {
bluetooth.startScanning({
serviceUUIDs: ["133d"],
seconds: 4,
onDiscovered: (peripheral) => {
console.log("Periperhal found with UUID: " + peripheral.UUID);
}
}).then(() => {
console.log("scanning complete");
}, (err) => {
console.log("error while scanning: " + err);
});
}
});
});
}
Having stepped through my app with the debugger, when bluetoothAdd()
is called in my HomeComponent, my scan()
function in BluetoothUtils works as expected and in one scenario, executes the console.log("error while scanning: " + err);
line, saying:
error while scanning: Bluetooth is not enabled
However, neither the then
or the catch
parts of the HomeComponent this._ble.scan()
promise are executed? Why is this? Can you compound Promises (i.e. a promise in a promise) as I am trying to do? or any ideas how ot debug this further?