I am trying to use await
function within a forEach
loop which is not working. My component.ts
code is:
myArray: number[] = [];
constructor() {
this.myArray = Array(2).fill(undefined);
}
obj = { '1': 'num 1', '2': 'num 2', '3': 'num 3' };
ngOnInit() {
this.func4().then().catch();
}
async func4() {
// for (var key in this.obj) {
Object.keys(this.obj).reverse().forEach(async (key) => {
console.log(this.obj[key], Date.now());
for (let i = 0; i < 2; i++) {
await this.func3(key, i).then().catch();
}
});
}
async func3(i: string, j: number) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('in function func3 ', i, j, Date.now());
resolve('hi');
}, 2000);
});
}
}
Surprisingly it works with for (var key in this.obj) {
but failing for Object.keys(this.obj).reverse().forEach(async (key) => {
where I want to loop through a reverse order in JSON object array.
StackBlitz
What am I missing here?
1