我目前正在学习更多关于角度和打字稿的异步方面的知识,如果我缺乏知识,请原谅我,我目前正面临一个问题,我正在尝试实现承诺以使包含 for 循环的函数在调用之前先完成下一个功能,
这是一个示例代码,其中目标是我有一个 for 循环来遍历所有表单,并且在循环中,是调用服务以获取要放入对象中的必要数据,然后继续使用所述创建一个新对象数据并将新创建的数据推送到数组中,在此函数结束后,下一个函数将运行以将数组提交给服务。
例如我有一个大小为 2 的表单,我希望在调用最后一个 resolve() 返回 submitObj() 并最终调用 sendTestObject() 之前结束 for 循环,
在 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();
}
在 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);
});
}