2017-04-25 77 views
-4

我想循環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; 
    } 
    } 
    } 

我在最後兩天卡在這裏...請幫助我解決這個問題

+0

爲什麼不能得到結果? – mast3rd3mon

+1

你能解釋一下函數的用途嗎?在會員級別存儲計數器似乎是錯誤的方法。從我收集的內容看,您似乎有要掃描的項目列表,然後一旦掃描完成,就不需要再次掃描。我只想從列表中刪除這些項目,而不是試圖維護一個計數器。應該更簡單。 – Brian

+0

如果您不使vendorbarcode成爲異步函數,那麼您試圖執行的操作是不可能的。 while循環不會等待異步操作,然後繼續執行異步/等待操作。 –

回答

0

我已通過將vendorbarcode(index,pickup列表)設置爲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) { 
      }); 
     } 
     }); 
    }