AWS中的lambda函数返回后,variables为null

我试图定义局部variables,然后调用lambda函数将值填充到我的本地variables:

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 

这里的问题是lambda.invokeasynchronous执行,并且在invokecallback函数完成之前执行最后一个console.log。

如果您需要从外部访问asynchronous调用完成的结果,则可以使用承诺。

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