4

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();
    });
};
1
  • Set up Lambda Proxy Integrations on API gateway and then code to give response in lambda. Commented May 19, 2019 at 11:33

2 Answers 2

4

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.