Search code examples
node.jsamazon-web-servicesrestaws-lambdaserverless

AWS Lambda returns 502 when using Promise.all()


Endpoint is returning 502 in every condition. I think my reponses are correctly structured but I still got 502 Bad Gateway error from my endpoint.

Responses was working when I was not dealing with Promise.all().

Timeout for this function is 30 seconds btw, but it doesn't take that long.

I have a handler like this:

module.exports.handler= async function (event, context, callback) {
  await Promise.all([promise1(), promise2()])
    .then((value) => {
      promise3(value[0], value[1])
        .then(() => {
          const response = {
            statusCode: 200,
            body: JSON.stringify({
              message: "Successful",
            }),
          };
          callback(null, response);
        })
        .catch((err) => {
          const response = {
            statusCode: 401,
            body: JSON.stringify({
              message: err,
            }),
          };
          callback(null, response);
        });
    })
    .catch((err) => {
      const response = {
        statusCode: 500,
        body: JSON.stringify({
          message: err,
        }),
      };
      callback(null, response);
    });
};

The error I am getting from the test from API Gateway:

Sat Dec 05 09:24:08 UTC 2020 : Endpoint response body before transformations: null
Sat Dec 05 09:24:08 UTC 2020 : Execution failed due to configuration error: Malformed Lambda proxy 
response
Sat Dec 05 09:24:08 UTC 2020 : Method completed with status: 502

Solution

  • You should stick to using await or .then, instead of trying to use both.

    Since your handler is already async you might as well use await.

    I've modified your code below so that it no longer uses .then (not tested).

    module.exports.handler= async function (event, context, callback) {
        try
        {
            var values = await Promise.all([promise1(), promise2()]);
    
            try
            {
                await promise3(values[0], values[1]);
                const response = {
                    statusCode: 200,
                    body: JSON.stringify({
                        message: "Successful",
                    })
                };
                callback(null, response);
            }
            catch(err)
            {
                const response = {
                    statusCode: 401,
                    body: JSON.stringify({
                        message: err,
                    })
                };
                callback(null, response);
            }
        }
        catch(err) 
        {
            const response = {
                statusCode: 500,
                body: JSON.stringify({
                    message: err,
                })
            };
            callback(null, response);
        }
    }