3

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),
    };
};

1 Answer 1

3

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),
    };
};
Sign up to request clarification or add additional context in comments.

1 Comment

How can I add a delay between each call?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.