I'm currently learning more about the asynchronous aspect of angular and typescript so forgive me if my knowledge is lacking, I am currently facing a problem where I'm trying to implement promises to make a function which contains a for loop finish first before calling the next function,
Here is a sample code where the goal is where I have a for loop to go through all forms and in the loop, is to call a service to get the necessary data to be placed into the object then proceed to create a new object with said data and pushing the newly created data into an array, which after this function ends and the next function will run to submit the array to a service.
For example I have a form with a size of 2, I would like the for loop to end before calling the last resolve() to return to submitObj() and finally calling sendTestObject(),
in the component.ts
submitObj() {
// call function to create object and wait for it to finish
// via a promise.then()
this.createTestObject().then((){
//then finally call another service to give created object
this.sendTestObject();
});
}
createTestObject() {
const testObjList: testActvity[] = [];
let count = 1;
return new Promise ((resolve) => {
// How do I make it so that this for loop goes in order
// and finishes first
// before going to the next line of code?
for (const i in this.testFormArray.controls) {
testObj = new Actvity();
let promise = new Promise((resolve,reject) =>{
this.testService.getTestData().then(res => {
console.log(count);
if (res) {
if (res.results) {
this.testArrayForm.controls[i].get('testForm').patchValue({
"Id": res.results.Id,
"type": res.results.type,
})
}
}
})}
resolve();
}
});
promise.then(()=> {
console.log("in then() of " + count);
testObj.testForm = this.testArrayForm.controls[i].get('testForm').value;
testObjList.push(testObj);
count ++;
})
//How do I wait for the for loop to finish first before running this?
console.log("FINISHED)"
resolve();
}
in the service.ts
getTestData(): Promise<any>{
let res = this.http.get("testData.json")
.toPromise()
.then( res => {
return res ;
}). catch (err => {
return err ;
});
return new Promise ((resolve, reject) => {
resolve(res);
});
}