2

I have an AWS Lambda Function A that calls another Lambda Function B For sake of discussion I want to invoke it synchronously - wait for results and process them. I want to do something like this in Lambda A:

let results = lambda.invoke(LambdaB);
// Do some stuff with results

The issue is that when I use the SDK APi to invoke Lambda B, I pass in a function that processes the results of that invocation. The processing function gets invoke and processes the results, but I'm noticing that the // Do some other stuff with results line is executing before that processing function completes, so the results are not available yet. I'm still somewhat new to the NodeJS way of doing things, so what is the paradigm to ensure that I have the results I want before I move on to more processing with Lambda A? Here is what I have in a nuthell:

// Lambda A code
let payLoad = undefined;
let functionName = "LambdaB";
let params = {
  FunctionName: functionName,
  InvocationType: "RequestResponse",
  LogType: "Tail",
  Payload: '{name: "Fred"}'
};

lambda.invoke(params, function(err,data) {
  if (err) {
    // process error
  } else {
    payLoad = JSON.parse(data.Payload);
    // payLoad is set properly here.
  }
});

console.log("Do stuff with results');
console.log("PAYLOAD=" + payLoad);  
// payLoad is undefined here
// How can I ensure it is set by the time I get here
// or do I need to use a different paradigm?

1 Answer 1

1

You will need to use async/await.

So your code will look like that :

exports.handler = async () => {
  // Lambda A code
  let functionName = "LambdaB";
  let result = undefined;
  let payload = undefined;
  let params = {
    FunctionName: functionName,
    InvocationType: "RequestResponse",
    LogType: "Tail",
    Payload: '{name: "Fred"}'
  };

  try {
    result = await lambda.invoke(params).promise();
    payload = JSON.parse(result.Payload);
  } catch (err) {
    console.log(err);
  }

  console.log("Do stuff with results');
  console.log(payload);
  return;
}

Watchout : the lambda handler has to be an async function to use async/await in it !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.