3

I tried to define local variable then call lambda function which populates the value to my local variable:

var listOfAliases = null;
lambda.invoke(params, function(err, data) {
    if (err) {
        //context.fail(err);
        console.log(`This is the ERROR execution =${err} =================================`);
        prompt(err);
    } else {
        //context.succeed('Data loaded from DB: '+ data.Payload);
        listOfAliases = JSON.stringify(data.Payload);
        console.log(`This is the VALIDE execution =${data.Payload} =================================`); //I can see this in the log with proper values
        console.log(`This is the VALIDE execution(listOfAliases) =${listOfAliases} =================================`); //I can see this in the log with proper values

    }
    callback(null, JSON.parse(data.Payload));
});

console.log(`This is the DB execution listOfAliases=${listOfAliases} =================================`); //I can see this in the log with NULL value
1
  • What params are you passing? Invoke is synchronous by default, using invoke type RequestResponse. So unless you have set it to type Event (which is async) then you're performing this synchronously. Commented May 7, 2017 at 13:15

1 Answer 1

2

The problem here is that lambda.invoke executes asynchronously and your last console.log executes before the invoke callback function completes.

If you need to access the result from outside one the asynchronous call completes, you could use a promise.

var promise = new Promise(function(resolve,reject){
  lambda.invoke(params, function(err, data) {
       if (err) {
           reject(err);    
       } else {
           resolve(JSON.stringify(data.Payload));
       }
  });
});
promise.then(function(listOfAliases){
  console.log('This is the DB execution listOfAliases ' + listOfAliases);
});
Sign up to request clarification or add additional context in comments.

3 Comments

The docs state that you have to specify async execution. Am I misunderstanding them? From the lambda invoke docs "By default, the Invoke API assumes RequestResponse invocation type. You can optionally request asynchronous execution by specifying Event as the InvocationType."
Here the Event InvocationType means that you can invoke lambda function and complete the api call without waiting for it to finish and give the result. But still it's a http request and at client side executes asynchronously.
One thing to note is that if you use Event InvocationType you would not receive the result from data parameter in the callback

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.