0

I'm trying to run an async function that send post request to the server and logs the response in the console. Whenever I run a for loop nothing is happening. I have checked a different similar questions here on stackoverflow but nothing is working in my case.

Note this code is for ionic + angular for android.

Below is the code for the function.

postAPI(suffixUrl, queryString, data, header: any = {}) {
    // console.log(suffixUrl + "\n=>", queryString + "\n=>", data + "\n=>", header);
    this.isDisabled = true;

    data = (header.is == 'yes') ? JSON.parse(data) : data;

    let type = this.fileNameSubStringFn(suffixUrl, '?');
    return new Promise(resolve => {
        this.http.post(this.con.baseUrl + suffixUrl + queryString, data)
          .subscribe(res => {
            // res = res.json();
            // res = JSON.parse(res.data);
            console.log("RES:", res);
            this.hideLoader();
            resolve(this.data);
            return;
          }, (err) => {
            this.logFn("ERROR:" + JSON.stringify(err));
            this.isDisabled = false;
            // this.isConnected = false;
          });
    });
}

Below is the code that is accessing the above function in-order to submit the data.

var i;

for (i = 0; i < summeriesArray.length; i++) {
    this.postAPI('service_summery', '', JSON.stringify(summeriesArray[i]), { is: 'yes', method: 'post' }).then(data => {
                this.hideLoader();
                this.toast("Successfully saved");
                console.log(data);
    });
}

Code inside this.postAPI is not executing which means the data is not being posted and I'm getting no errors so I don't know what is going on here.

I'm expecting the this.postAPI to run successfully in a for lop.

Thank you, posted with Love.

1 Answer 1

1

You can use the await keyword, so you wait for the next iteration until the completion of the 'postAPI'.

for (i = 0; i < summeriesArray.length; i++) {
  const data = await this.postAPI('service_summery', '', JSON.stringify(summeriesArray[i]), { is: 'yes', method: 'post' })
  this.hideLoader();
  this.toast("Successfully saved");
  console.log(data);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.