简体   繁体   English

离子等待方法完成,然后再继续

[英]Ionic wait for method to complete before continuing

I have the following method.我有以下方法。

 async getuserdevicesIDs() {
  let timesDone = 0;
  // tslint:disable-next-line: no-var-keyword
  const viewDevicesLink = '/user/devices/view/'; // parameter: email
  const xhr = new XMLHttpRequest();
  // xhr.open('POST', this.AUTH_SERVER_ADDRESS + '/user/devices/view/', true);
  xhr.open('POST', this.AUTH_SERVER_ADDRESS  + viewDevicesLink, true);

  xhr.setRequestHeader('Content-type', 'application/JSON;charset=UTF-8');
  console.log(this.auth.getUserID());
  const email = this.auth.getUserID().toString();
  const us = new User();
  us.name = '';
  us.email = 'richard@gmail.com';
  us.password = '';


  xhr.send(JSON.stringify(us));

  xhr.addEventListener('readystatechange', processRequest, false);

  xhr.onreadystatechange = processRequest;

  function processRequest(e) {
      // tslint:disable-next-line: triple-equals
      if (xhr.readyState == 4 && xhr.status == 200) {
          // tslint:disable-next-line: triple-equals
          if (timesDone == 0) {
              // tslint:disable-next-line: prefer-const
              const response  = xhr.response;
              timesDone++;
              return response;

          }
      // tslint:disable-next-line: triple-equals
      } else if (xhr.readyState == 4) {
          alert('server error: ' + xhr.status + ', response is: ' + xhr.responseText);
          timesDone++;
          return null;
      }

  }

} 

that is working fine but when i call the method like this这工作正常但是当我调用这样的方法时

 var IDs = await this.getuserdevicesIDs();
  alert(IDs[0]); 

then the alert fires before the getuserdevicesIDs() method has completed even if I await it.然后即使我在等待它,警报也会在 getuserdevicesIDs() 方法完成之前触发。 Any idee on how i can force the alert to wait for the method to finish?关于如何强制警报等待方法完成的任何想法? Thanks for any help谢谢你的帮助

Try returning a Promise inside getuserdevicesIDs() function like this尝试像这样在 getuserdevicesIDs() function 中返回 Promise

async getuserdevicesIDs() {
     return await new Promise((resolve, reject) => {
     //your code here ...
     resolve(value); // when you want to return a value in promise
     }
}

When you want to call the method当你想调用方法时

this.getuserdevicesIDs().then(response => {}).catch(err => {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM