Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable is null after returned from lambda function in AWS

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
like image 603
Ahmed Aziz Avatar asked Aug 02 '26 08:08

Ahmed Aziz


1 Answers

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);
});
like image 136
Asanka Avatar answered Aug 03 '26 22:08

Asanka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!