有没有一种方法可以从node.js同步调用AWS Lambda? [英] Is there a way to invoke AWS Lambda synchronously from node.js?

查看:136
本文介绍了有没有一种方法可以从node.js同步调用AWS Lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JS SDK通过我的node.js应用程序调用Lambda,通过AWS Lambda从现有应用程序运行特定功能.由于我要覆盖现有功能,因此必须保留其基本结构,即:

I'm trying to run a specific function from an existing app via AWS Lambda, using the JS SDK to invoke Lambda from my node.js app. Since I'm overwriting the existing function, I'll have to keep its basic structure, which is this:

overwrittenFunction = function(params) {
    //get some data
    return dataArray;
}

.. so,因此我需要返回一个可以返回的数组,如果我想保留lib的基础结构,请使用相同的数组.现在,据我所知,Lambda调用是异步的,因此不可能可以执行以下操作:

..so I need to end up with an array that I can return, if I'm looking to keep the underlying structure of the lib I use the same. Now as far as I know, Lambda invocations are asynchronous, and it's therefore not possible to do something like this:

overwrittenFunction = function(params) {
    lambda.invoke(params, callback);
    function callback(err,data) {
        var dataArray = data;
    }
    return dataArray;
}

(我也曾尝试过用promise和async/await做类似的事情).

(I've also tried similar things with promises and async/await).

afaik我现在有两个选择:以某种方式弄清楚如何执行同步Lambda调用,或修改我的库/现有应用程序(如果可能的话,我宁愿不这样做).

afaik I have two options now: somehow figure out how to do a synchronous Lambda invocation, or modify my library / existing app (which I would rather not do if possible).

有什么办法做这样的事情,并以某种方式返回我期望的值吗?

Is there any way to do such a thing and somehow return the value I'm expecting?

(我正在使用节点v8.9.4)

(I'm using node v8.9.4)

推荐答案

Lambda和async/await有点棘手,但是以下内容对我有用(正在生产中):

Lambda and async/await are a bit tricky, but the following is working for me (in production):

const lambdaParams = {
    FunctionName: 'my-lambda',
    // RequestResponse is important here. Without it we won't get the result Payload
    InvocationType: 'RequestResponse',
    LogType: 'Tail', // other option is 'None'
    Payload: {
        something: 'anything'
    }
};

// Lambda expects the Payload to be stringified JSON
lambdaParams.Payload = JSON.stringify(lambdaParams.Payload);

const lambdaResult = await lambda.invoke(lambdaParams).promise();

logger.debug('Lambda completed, result: ', lambdaResult.Payload);

const resultObject = JSON.parse(lambdaResult.Payload)

通过尝试/捕获将其包装起来,然后前往城镇.

Wrap it all up in a try/catch and go to town.

这篇关于有没有一种方法可以从node.js同步调用AWS Lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆