【发布时间】:2016-05-28 12:29:03
【问题描述】:
我正在编写一个基于 Angular2 的移动应用程序,将 Typescript 与 Nativescript 运行时结合使用,但在使用 Promises 时遇到了一些问题。我有一个 HomeComponent,我希望能够从中调用各种蓝牙功能。这些需要人工交互(如选择设备)和蓝牙扫描的等待时间,因此它们需要几秒钟才能完成。
我想将这些方法抽象为promise,所以我这样做了:
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._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);
});
}
});
});
}
使用调试器逐步完成我的应用程序后,当在我的 HomeComponent 中调用 bluetoothAdd() 时,我在 BluetoothUtils 中的 scan() 函数按预期工作,在一种情况下,执行 console.log("error while scanning: " + err); 行,说:
扫描时出错:蓝牙未启用
但是,HomeComponent this._ble.scan() 承诺的 then 或 catch 部分都没有执行?为什么是这样?你能像我试图做的那样复合 Promises(即 Promise 中的 Promise)吗?或任何想法如何进一步调试?
【问题讨论】:
-
避免使用
Promiseconstructor antipattern!请注意,您甚至没有在任何地方调用resolve或reject,这就是为什么.scan()返回的承诺永远不会解决。
标签: javascript typescript angular promise nativescript