user866364
user866364

Reputation:

Invoke function async on AWS Lambda

I'm trying to invoke a function as async because I don't wan't to wait the response.

I've read the AWS docs and there says to use InvocationType as Event but it only works if I do a .promise().

not working version:

lambda.invoke({
  FunctionName: 'rock-function',
  InvocationType: 'Event',
  Payload: JSON.stringify({
    queryStringParameters: {
      id: c.id,
      template: c.csvTemplate
    }
  })
})

working version:

lambda.invoke({
  FunctionName: 'rock-function',
  InvocationType: 'Event',
  Payload: JSON.stringify({
    queryStringParameters: {
      id: c.id,
      template: c.csvTemplate
    }
  })
}).promise()

Anyone could me explain why it happens?

Upvotes: 0

Views: 1790

Answers (1)

Dave Maple
Dave Maple

Reputation: 8402

invoke returns an AWS.Request instance, which is not automatically going to perform a request. It's a representation of a request which is not sent until send() is invoked.

That's why the latter version works but the former does not. The request is sent when .promise() is invoked.

// a typical callback implementation might look like this
lambda.invoke({
    FunctionName: 'rock-function',
    InvocationType: 'Event',
    Payload: JSON.stringify({
        queryStringParameters: {
            id: c.id,
            template: c.csvTemplate,
        },
    }),
}, (err, data) => {
    if (err) {
        console.log(err, err.stack);
    } else {
        console.log(data);
    }
});

// ... or you could process the promise() for the same result
lambda.invoke({
    FunctionName: 'rock-function',
    InvocationType: 'Event',
    Payload: JSON.stringify({
        queryStringParameters: {
            id: c.id,
            template: c.csvTemplate,
        },
    }),
}).promise().then(data => {
    console.log(data);
}).catch(function (err) {
    console.error(err);
});

Upvotes: 4

Related Questions