How to assign for loop promise result to the outside variable in Expressjs, Typescript?

Viewed 25
export const getSObjectFields = async (request: Request, response: Response) => {
if (!request.body) { return response.status(401).json({ error: 'No SObject Selected' }); }
let selectedSObject = request.body;
let sObjectsDetails: any = [];
selectedSObject.forEach((element: string, _index: number) => {
    let promiseDescribeSObject = describeSObject(request, response, element);
    promiseDescribeSObject.then((res) => {
        sObjectsDetails.push(res);
    }).catch((err) => {
        console.error('Error: ', err);
    });
});
return response.status(200).json(sObjectsDetails);

}

I do have a function that call an API with parameter describeSObject(request, response, 'objectName'). I want to iterate the describeSObject function and save the result to the outside variable of for loop.

1 Answers

You can use async/await syntax and use map and Promise.all to resolve all promises of the array together.

export const getSObjectFields = async (request: Request, response: Response) => {
  if (!request.body) { return response.status(401).json({ error: 'No SObject Selected' }); }
  let selectedSObject = request.body;
  let sObjectsDetails = await Promise.all(selectedSObject.map(async (element: string) => await describeSObject(request, response, element)))
  return response.status(200).json(sObjectsDetails);
}

Related