while循环不等待函数执行

时间:2017-04-25 13:48:50

标签: while-loop

我正在尝试在循环中循环对象但是我无法得到结果。实际上我假设计数器的值在执行内部函数while循环后递增...但是值在函数执行之前,计数器正在增加......我不知道为什么会发生这种情况......

这是我的test.ts

export class HelloIonicPage {
_i: number = 0;
barcode(index, pickuplist) {
   BarcodeScanner.scan()
   .then((barcodeData) => {
      if (barcodeData.cancelled) {
        alert("User cancelled the action!");
        return false;
      }
      this.bartxt = barcodeData.text;
      if (this.bartxt != '') {
        this.authservice.testFunction(this.bartxt)
          .subscribe(data => {
            if (data !== '') {
              alert("Scanned successfully!");
              alert(this._i);                     //here the value of i should be 0, but it showing 2
              if (this._i == (this.totalorders - 1)) {
                 alert(this._i + " _index");
                 this.finalacceptvendor(index, pickuplist);
               } else {
                 alert(this._i + " _index");
                 this.vendorbarcode(index, pickuplist);
               }
            } else {
              this.vendorbarcode(index, pickuplist);
              alert( Wrong QR Code);
            }
          });
        }
      });
     }
vendorbarcode(index, pickuplist) {
    this.totalorders = 2;
    while (this._i < this.totalorders) {
      alert(this._i + "_index");           //here the value of i = 0
        this.barcode(index, pickuplist);
      this._i = this._i + 1;
    }
   }
  }

我在最近两天被困在这里...请帮忙解决这个问题

1 个答案:

答案 0 :(得分:0)

我通过将vendorbarcode(index,pickuplist)设置为asyn函数解决了这个问题,如下所示:

public vendorbarcode = function (index, pickuplist) {
    this.totalorders = this.pickuplist[index].Total_Orders;
    this.vendorid = this.pickuplist[index].VendorId;
    // async stuff, like fetching users from server, returning a response
    this.authservice.getorderidsFunction(this.vendorid)
      .subscribe(data => {
        this.orderids = data[this._i].OrderId;
        while (this._i < data.length) {
          this.barcode(index, pickuplist)
            .then(function (response) {
            });
        }
      });
  }