2017-03-16 63 views
3

如何在AWS Lambda處理程序之外運行異步函數並在處理函數中使用其輸出?我需要在處理函數運行之前異步初始化各種數據庫連接。這樣,活動數據庫連接可以在容器重用時生存。如何在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

你將不得不創建一個承諾,然後解決每當內部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)) 
}