简体   繁体   English

在 AWS Lambda 上调用异步函数

[英]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() .我已经阅读了 AWS 文档,那里说使用InvocationType作为Event但它只有在我执行.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?任何人都可以解释为什么会发生?

invoke returns an AWS.Request instance, which is not automatically going to perform a request. invoke返回一个AWS.Request实例,它不会自动执行请求。 It's a representation of a request which is not sent until send() is invoked.它是在调用send()之前不会发送的请求的表示。

That's why the latter version works but the former does not.这就是为什么后者有效而前者无效的原因。 The request is sent when .promise() is invoked.当调用.promise()时发送请求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM