Invoke function async on AWS Lambda

孤人 提交于 2020-06-13 08:49:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/54768574/invoke-function-async-on-aws-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!