等待功能结束,然后再开始下一个

我正在使用Angular开发Ionic v4。

在我的项目中,我使用BLE与覆盆子通信。

我有几个步骤:

  1. 我周围的搜索设备
  2. 连接到该设备
  3. 激活通知
  4. 发送消息

目前我有类似的东西:

this.ble.scan().subscribe(result => {
  if (device === theDeviceIWant) {
    this.ble.connect(device.id).subscribe(result => {
      this.ble.startNotification(infosaboutDevice).subscribe(result => {
        // Message 1
        this.ble.writeWithoutResponse(infos,message).then(result => {
          // Message 2
          this.ble.writeWithoutResponse(infos,message).then(result => { 
            // Message 3
            this.ble.writeWithoutResponse(infos,message).then(result => {
              // Message X
              this.ble.writeWithoutResponse(infos,message).then(result => {
              })
            })
          })
        })
      })
    })
  })
}

我想做这样的事情:

this.myScan();
this.myConnect();
this.myNotification();
this.myMessage('Text 1');
this.myMessage('Text 2');
this.myMessage('Text X');

问题:我的功能“ myConnect”不要等待“ myScan”的结尾开始。因此,“ myConnect”所需的某些东西是在“ myScan”中完成的。

我已经尝试使用“异步/等待”,但无法正常工作。我认为我没有正确使用它:

 await this.myConnect().then(async () => {
       await this.myNotification().then(async () => {
           await this.myMessage('03020000').then(async () => {
               await this.myMessage('010100').then(async () => {
                   await this.myMessage('020200' + this.random.toString(16));
               });
           });
       });
   });

帮助我了解如何创建一个函数,该函数等待上一个函数的结尾开始:D

hongchengge 回答:等待功能结束,然后再开始下一个

只需使用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. 连接到该设备
  3. 激活通知
  4. 发送消息

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

大家都在问