I've encountered a problem while developing my Angular2-based mobile app using Typescript with Nativescript runtime. The issue revolves around Promises when working with Bluetooth functions in my HomeComponent. These Bluetooth functions require human interaction and have wait periods for scanning, which results in delayed completion of several seconds.
To tackle this issue, I decided to abstract these methods as promises. Here's what I did:
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);
});
}
});
});
}
During debugging, when bluetoothAdd()
is called in my HomeComponent, the scan()
function in BluetoothUtils behaves as expected. Under certain circumstances, it even displays an error message saying:
error while scanning: Bluetooth is not enabled
However, neither the then
nor the catch
parts of the HomeComponent's this._ble.scan()
promise are executed. Why is this happening? Can you nest Promises (i.e., a promise within a promise) as I am attempting here? Any suggestions on how to debug this further?