只需使用async / await或then
await this.myConnect(); // this awaits the Promise returned by myConnect to be resolved
await this.myNotification(); // same for this Promise
await this.myMessage('03020000'); // and so on...
await this.myMessage('010100');
await this.myMessage('020200' + this.random.toString(16));
,
关键字await使JavaScript等待该承诺完成并
返回其结果。
因此您无需在then
中使用await this.myConnect().then(()=>{});
使用await this.myConnect()
;
下面是一个示例,可以帮助您更好地了解
function SignalOne() {
return new Promise((resolve,reject) => {
setTimeout(()=>{
resolve('Hello iam signal one');
},2000);
});
}
function SignalTwo() {
return new Promise((resolve,reject) => {
setTimeout(()=>{
resolve('Hello iam signal Two');
},1000);
});
}
async function sendSignal() {
let one = await SignalOne();
let two = await SignalTwo();
console.log(one);
console.log(two);
}
sendSignal();
,
尝试一下:
AppCompat
,
这本质上就是承诺的目的。
承诺是代表最终完成或失败的对象
异步操作。
You can read up about Promises here。当您阅读完这些内容后,我在下面为您提供了一个示例,以演示如何使用Promise
:
//Wrap the operation you want to wait for in a Promise (in this case: setTimeout)
const promise = new Promise((resolve,reject) => {
setTimeout(() => {
resolve('3 seconds have passed');
},3000);
});
//Once the operation is resolved the callback in the .then will be called
promise.then(val => document.querySelector('#target').innerHTML = val);
<div id="target">This message will change once the operation is resolved in 3 seconds.</div>
,
我会拥抱Observables。看着你想要的。.
- 我周围的搜索设备
- 连接到该设备
- 激活通知
- 发送消息
1和2将与switchMap
链接在一起,因为响应彼此依赖。然后3和4可以按顺序执行,但彼此不依赖,因此我们可以在其中使用concat
。 (如果这不是正确的流量,请使用这两个运算符进行相应的调整。)
所以我建议以下内容:
import { never } from 'rxjs';
import { switchMap,concat } from 'rxjs/operators';
// ...
this.ble.scan().pipe(
switchMap((device) => {
if (device === theDeviceIWant) {
return this.ble.connect(device.id)
}
// terminates rest of code
return never();
}),concat(
this.ble.startNotification(...),this.ble.writeWithoutResponse(...)
)
).subscribe(data => console.log(data))
,
您是如此亲密!而不是使用.then
和 async
而是仅使用其中一个。以下是完成您要完成的工作的几种方法:
使用.then
:
这是典型的链接语法。可以使用.then()
链接承诺并传递函数。如果返回值是一个值(不是Promise
),则它将解析为该值。但是,如果 did 返回一个Promise
,它将链接在一起,下一个.then()
将解析为“内部”异步调用结果。
// Message 1
return this.ble.writeWithoutResponse(infos,message).then(result1 => {
// Message 2
return this.ble.writeWithoutResponse(infos,message);
}).then(result2 => {
// Message 3
return this.ble.writeWithoutResponse(infos,message);
)}.then(result3 => {
// Message X
return this.ble.writeWithoutResponse(infos,message);
}).then(result4 => { })
使用async
/ await
这种方法可以达到相同的结果,但是使用特殊的关键字将诺言自动链接在一起。 async
/ await
允许您跳过.then()
和return
调用,以便您可以像调用异步函数一样调用它们。
// Message 1
let result1 = await this.ble.writeWithoutResponse(infos,message)
// Message 2
let result2 = await this.ble.writeWithoutResponse(infos,message);
// Message 3
let result3 = await this.ble.writeWithoutResponse(infos,message);
// Message X
let result4 = await this.ble.writeWithoutResponse(infos,message);
要了解有关Promise
和异步javascript的更多信息,请查看以下资源:
本文链接:https://www.f2er.com/3072072.html