使用 Promise.all() 时 AWS Lambda returns 502

AWS Lambda returns 502 when using Promise.all()

端点在每种情况下都返回 502。我认为我的响应结构正确,但我的端点仍然收到 502 Bad Gateway 错误。

当我不处理 Promise.all() 时响应有效。

这个函数的超时时间是 30 秒顺便说一下,但不会花那么长时间。

我有一个这样的处理程序:

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

我从 API 网关测试中得到的错误:

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

您应该坚持使用 await.then,而不是同时使用两者。

由于您的处理程序已经 async 您不妨使用 await.

我已经修改了下面的代码,因此它不再使用 .then(未测试)。

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