Invoke AWS Lambda and return response to API Gateway asyncronously

前端 未结 4 1513
醉梦人生
醉梦人生 2021-01-06 12:02

My use case is such that I\'ll have an AWS Lambda front ended with API Gateway.

My requirement is that once the Lambda is invoked it should return a 200 OK response

4条回答
  •  伪装坚强ぢ
    2021-01-06 13:01

    If anyone is interested, here is the code you can use to do the two lambdas approach. The code below is the first lambda that you should setup which would then call the second, longer running, lambda. It takes well under a second to execute.

    const Lambda = new (require('aws-sdk')).Lambda();
    
    /**
     * Note: Step Functions, which are called out in many answers online, do NOT actually work in this case.  The reason
     * being that if you use Sequential or even Parallel steps they both require everything to complete before a response
     * is sent.  That means that this one will execute quickly but Step Functions will still wait on the other one to
     * complete, thus defeating the purpose.
     *
     * @param {Object} event The Event from Lambda
     */
    exports.handler = async (event) => {
        let params = {
          FunctionName: "",
          InvocationType: "Event",  // <--- This is KEY as it tells Lambda to start execution but immediately return / not wait.
          Payload: JSON.stringify( event )
        };
    
        // we have to wait for it to at least be submitted. Otherwise Lambda runs too fast and will return before
        // the Lambda can be submitted to the backend queue for execution
        await new Promise((resolve, reject) => {
            Lambda.invoke(params, function(err, data) {
                if (err) {
                    reject(err, err.stack);
                }
                else {
                    resolve('Lambda invoked: '+data) ;
                }
            });
        });
    
        // Always return 200 not matter what
        return {
            statusCode : 200,
            body: "Event Handled"
        };
    
    };
    

提交回复
热议问题