I have a code snippet that looks like this:
export class MyHandler {
entry = async (data: string[]): Promise<Map<string, string>> {
const response: Map<string, string> = new Map();
Promise.all(
data.map(async (item) => {
const apiGetDataRequest = {
data: item
};
const apiGetDataResponse = await this.client.apiCall(apiGetDataRequest);
return apiGetDataResponse.data;
});
).then((results) => {
for (const result of results) {
const value = myFirstMethod([1, 2, 3]);
response.set(result, value);
}
});
return response;
};
myFirstMethod = (items: number[]): string {
const result = mySecondMethod(items, 'Test');
console.log(result);
return result;
};
mySecondFunction = (items: number[]): string {
let finalResult = "";
Promise.all(
items.map(async (item) => {
const apiCallRequest = {
data: item
};
const apiCallResponse = await this.client.apiCall(apiCallRequest);
return apiCallResponse.data;
});
).then((results) => {
for (const result of results) {
finalResult = finalResult + ', ' + result;
}
});
return finalResult;
};
}
The problem I am facing is that mySecondFunction
returns before all promises are completed, causing the result
variable in myFirstMethod
to always be an empty string. How can I make sure that mySecondFunction
waits for all promises to finish before returning?