Search code examples
javascriptnode.jslambdaasync-await

Waiting for forEach loop in aws lambda function


How can I wait for the forEach loop to finish before the return statement is executed in aws lambda?

module.exports.shipments = async (event) => {
    const axios = require("axios");
    let data = JSON.parse(event.body);
    let url = data.apiURL + "/api/1.1/wf/bulkshipments/initialize";
    let patchURL = data.apiURL + "/api/1.1/obj/company/" + data.companyID;

    data.shipments.forEach((item, index, array) => {
        axios.post(url,{
        batchID: data.batchID,
        companyID: data.companyID,
        shipment: item})
    });

    return {
      statusCode: 200,
      body: JSON.stringify({
        message: 'Created successfully!',
        totalShipments: data.shipments.length,
      }, null, 2),
    };
};

Solution

  • You're already using async, so use map to return a list of promises, and await them all with Promise.all():

    module.exports.shipments = async (event) => {
        const axios = require("axios");
        let data = JSON.parse(event.body);
        let url = data.apiURL + "/api/1.1/wf/bulkshipments/initialize";
        let patchURL = data.apiURL + "/api/1.1/obj/company/" + data.companyID;
        
        let promises = data.shipments.map(item =>
            axios.post(url, {
                batchID: data.batchID,
                companyID: data.companyID,
                shipment: item})
            })
        );
    
        await Promise.all(promises);
    
        return {
          statusCode: 200,
          body: JSON.stringify({
            message: 'Created successfully!',
            totalShipments: data.shipments.length,
          }, null, 2),
        };
    };
    

    To have each call wait, instead of firing all the post requests at the same time, use a for...of loop:

    module.exports.shipments = async (event) => {
        const axios = require("axios");
        let data = JSON.parse(event.body);
        let url = data.apiURL + "/api/1.1/wf/bulkshipments/initialize";
        let patchURL = data.apiURL + "/api/1.1/obj/company/" + data.companyID;
    
        for (let item of data.shipments) {
            await axios.post(url, {
                batchID: data.batchID,
                companyID: data.companyID,
                shipment: item})
            });
        }
    
        return {
          statusCode: 200,
          body: JSON.stringify({
            message: 'Created successfully!',
            totalShipments: data.shipments.length,
          }, null, 2),
        };
    };