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

时间:2019-09-26 15:33:10

标签: javascript asynchronous ionic-framework async-await

我有以下方法。

 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;
      }

  }

} 

那很好,但是当我调用这样的方法

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

然后,即使我等待,警报也会在getuserdevicesIDs()方法完成之前触发。关于如何强制警报等待方法完成的任何想法?感谢您的帮助

1 个答案:

答案 0 :(得分:0)

尝试像这样在getuserdevicesIDs()函数中返回Promise

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

当您要调用方法

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