Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 49290

For loop an HTTP request logical error

$
0
0

@dmlkl wrote:

Hello,

Can anyone guide me on this? Below is the sample code. I tried to call an HTTP request inside the for loop, but the loop doesn’t wait for HTTP request finish already enter the next loop.

  • requestService.GetTelemetryData is the HTTP request.
GetGeneralInfo(){

for (let i = 0; i < deviceData.length; i++) {
conso.log("Loop Start")
            this.requestService.GetTelemetryData(loginAcc['token'], deviceData[i]["id"]["id"]).then((telemetryData) => {

              console.log("After GetTelemetryData()");
              let status = JSON.parse(telemetryData['status']);

              if (status == 401) {
                console.log("Token Expired...")

                this.requestService.RefreshToken(loginAcc['token'], loginAcc['refreshToken']).then(refreshTokenResponse => {

                 //i need to terminated the for loop and recall this method with new token
                  this.GetGeneralInfo();
                });

              }
              else if (status == 200) {
                console.log("Token is valid and data is given....")
                let data = JSON.parse(telemetryData['data']);
              }
            })
          }
}


The codes will continue for loop without waiting for the HTTP request finish. Let say the device data length is 2, for loop will print “Loop start” twice then only print "After GetTelemetryData()"

Currently

“Loop Start”
“Loop Start”
“After GetTelemetryData()”
“After GetTelemetryData()”

Expectation

“Loop Start”
“After GetTelemetryData()”
“Loop Start”
“After GetTelemetryData()”

Can guide me on this? Thanks.

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 49290

Trending Articles