簡體   English   中英

離子等待方法完成,然后再繼續

[英]Ionic wait for method to complete before continuing

我有以下方法。

 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() 方法完成之前觸發。 關於如何強制警報等待方法完成的任何想法? 謝謝你的幫助

嘗試像這樣在 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
     }
}

當你想調用方法時

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM