Compound Promises in Typescript / Javascript? -
i writing angular2 based mobile app, using typescript nativescript runtime, facing issues promises. have homecomponent, able call various bluetooth functions. these require human interaction (like selecting device) , wait periods bluetooth scan, take several seconds complete.
i want abstract methods promises, have done this:
homecomponent.ts:
bluetoothadd() { this.isscanning = true; this._ble.scan().then( // log 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 imported above 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 uuid: " + peripheral.uuid); } }).then(() => { console.log("scanning complete"); }, (err) => { console.log("error while scanning: " + err); }); } }); }); }
having stepped through app debugger, when bluetoothadd()
called in homecomponent, scan()
function in bluetoothutils works expected , in 1 scenario, executes console.log("error while scanning: " + err);
line, saying:
error while scanning: bluetooth not enabled
however, neither then
or catch
parts of homecomponent this._ble.scan()
promise executed? why this? can compound promises (i.e. promise in promise) trying do? or ideas how ot debug further?
there's few problems.
1/ you're using anti pattern. there's no need create new promise in scan
since you're dealing promises.
2/a) if want use anti pattern, need call resolve
, reject
functions, i.e. in current situation new promise never resolved nor rejected, , therefore "main" promise in scan
never resolved or rejected either.
2/b) better solution: return promises created. if don't return become separate promise branches , won't influence "main" promise branch in scan
, i.e.:
export function scan() { return bluetooth.hascoarselocationpermission().then( (granted) => { if (!granted) { return bluetooth.requestcoarselocationpermission(); } else { return bluetooth.startscanning({ serviceuuids: ["133d"], seconds: 4, ondiscovered: (peripheral) => { console.log("periperhal found uuid: " + peripheral.uuid); } }).then(() => { console.log("scanning complete"); }, (err) => { console.log("error while scanning: " + err); }); } }); }
note 3 added return
s: 1 @ top of scan
, before bluetooth.requestcoarselocationpermission
, bluetooth.startscanning
if want know other promise anti patterns exist, here's great resource
Comments
Post a Comment