I have been trying to understand the right way to use a for loop for an array of promises. In my code, my array has 3 elements, but it only has data the first time through the loop.
private populateRequest(connection: Connection, myArray: any[], containerId: string): Promise<void> {
// tslint:disable-next-line:no-shadowed-variable
return new Promise(async (resolve, reject) => {
const promises: Array<Promise<SomeType>> = [];
let status = '';
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < myArray.length; i++) {
const data = await this.getResolvedPromise(myArray[i])
.then(response => response)
.catch(err => console.log(err));
if (this.flags.hasOwnProperty('prop1')) {
status = 'Active';
} else if (this.flags.hasOwnProperty('prop2')) {
status = 'Inactive';
} else if (data[0]['WidgetProp1'] === 'Active') {
status = 'Inactive';
} else if (data[0]['WidgetProp1'] === 'Inactive') {
status = 'Active';
}
const myMetaObj = {
prop3: data[0]['WidgetProp3'],
status
};
const myMetaMember = {
ContainerId: containerId,
ContentEntityId: data[0]['WidgetId'],
Body: data[0]['WidgetBody'],
Metadata: myMetaObj
};
promises.push(myMetaMember);
}
Promise.all(promises)
.then(() => resolve())
.catch(err => reject(err));
});
}
private getResolvedPromise(target: Promise<any>): Promise<any> {
// tslint:disable-next-line:no-any
return new Promise((resolve, reject) => {
// tslint:disable-next-line:no-any
Promise.all([target])
.then(() => resolve(target))
.catch(err => reject(err));
});
}
The push works as intended the first time, but not subsequently.
I understand this is because of async code and calls not finishing, but am not sure why my Promise.all()
doesn't work correctly.
Halps?