Node.js 从AWS中的lambda函数返回后,变量为null
我尝试定义局部变量,然后调用lambda函数,该函数将值填充到局部变量:Node.js 从AWS中的lambda函数返回后,变量为null,node.js,amazon-web-services,aws-lambda,Node.js,Amazon Web Services,Aws Lambda,我尝试定义局部变量,然后调用lambda函数,该函数将值填充到局部变量: var listOfAliases = null; lambda.invoke(params, function(err, data) { if (err) { //context.fail(err); console.log(`This is the ERROR execution =${err} =================================`);
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.invoke异步执行,并且在invoke回调函数完成之前执行最后一个console.log 如果需要从异步调用完成的外部访问结果,可以使用承诺
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);
});
你路过的是哪位女士?默认情况下,调用是同步的,使用调用类型
RequestResponse
。因此,除非您将其设置为typeEvent
(异步),否则您将以同步方式执行此操作。文档说明您必须指定异步执行。我误解他们了吗?在lambda调用中,“默认情况下,调用API采用RequestResponse调用类型。您可以通过将事件指定为调用类型来选择请求异步执行。”这里,事件调用类型意味着您可以调用lambda函数并完成API调用,而无需等待它完成并给出结果。但它仍然是一个http请求,在客户端异步执行