Joey Yi Zhao
Joey Yi Zhao

Reputation: 42644

How to http status code when return promise in lambda?

Below is my lambda function. It returns a promise instead using the callback. I wonder how I can return different http status code to API gateway?

exports.handler = async (event, context) => {

    return new Promise((resolve, reject) => {
        const options = {
            ...
        };

        const req = http.request(options, (res) => {
          resolve('Success');
        });

        req.on('error', (e) => {
          reject(e.message);
        });

        // send the request
        req.write('');
        req.end();
    });
};

Upvotes: 4

Views: 3139

Answers (2)

mayank  nayyar
mayank nayyar

Reputation: 134

With the new Node.js 8.10 runtime, there are new handler types that can be declared with the “async” keyword or can return a promise directly.

The new handler types are alternatives to the callback pattern, which is still fully supported.

As pointed out in the other answer, either you can directly return the status code with the help of using “async” keyword or you can return the promise directly. Please refer to the undermentioned code which directly returns the promise from the lambda function.

exports.handler = (event, context) => {
    return new Promise ((resolve, reject) => {
        resolve()
    })
    .then (()=>{
        return {
            statusCode : 200
        }
    })
    .catch(() =>{
        return {
            statusCode : 400
        }
    })
}

Also, please refer to the undermentioned link that gives the in detail idea about how promises and async-await eliminates the callback based approach.

https://aws.amazon.com/blogs/compute/node-js-8-10-runtime-now-available-in-aws-lambda/

Upvotes: 4

Melbourne2991
Melbourne2991

Reputation: 11797

There is no need to return a promise as the async keyword will do that for you:

exports.handler = async (event, context) => {
   return {
        statusCode: 201, // or whatever status code you want
        headers: {},
        body: JSON.stringify({})
    };
}

Upvotes: 0

Related Questions