如何在AWS Lambda处理程序之外运行异步函数并在处理函数中使用其输出?我需要在处理程序函数运行之前异步初始化各种数据库连接。这样,活动数据库连接可以在容器重用时继续存在。
示例:
var i = 'immediate start';
setTimeout(function(){
i = 'delayed start';
}, 5000);
module.exports.handler = function (event, context, callback) {
console.log(i);
//outputs `immediate start` whereas I need to have i = `delayed start` here.
}
答案 0 :(得分:1)
您必须创建一个承诺,然后在触发setTimeout()
内部的回调函数时解析承诺。像这样:
module.exports.handler = function (event, context, callback) {
var i = 'immediate start';
return new Promise((resolve, reject) => {
setTimeout(() => {
i = 'delayed start';
resolve()
})
})
.then(()=>console.log(i))
}