[英]AWS Lambda nodejs mysql query inside loop is not working
module.exports.handler = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
let index = 0;
var client = mysql.createConnection({
host: process.env.rds_host,
user: process.env.rds_username,
password: process.env.rds_password,
port: process.env.rds_port
});
client.connect((err) => {
if (err) throw err;
console.log("Connected!");
});
let array = [];
let queries = ["query1", "query2", "query3", "query4"];
queries.map(q => {
array.push(getQueryResult(client, q));
});
Promise.all(array).then(result => {
console.log(result);
});
callback(null, {});
};
const getQueryResult = async (client, query) => {
return new Promise((resolve, reject) => {
client.query(query, function (err, result) {
if (err) {
reject(err);
}
resolve(result);
});
});
};
以上是我的 lambda 腳本,用於從 mysql 執行多個查詢。 問題是我沒有從上面的腳本中得到任何結果和錯誤消息。 請幫助我的腳本中缺少某些內容?
上面的代碼存在兩個或三個(潛在)問題:
由於typeof
客戶端謂詞未返回 true,因此您的 if 語句未得到評估。
您的mysql
端口與您的localhost
端口沖突(假設)
像這樣更改您的 if 塊:
// check if `dotenv` has been called if you use it
require('dotenv').config();
// access the state property on mysql object
// if you have closed your connection previously
// this will get evaluated by the parser
if (mysql.state === "disconnected") {
var client = mysql.createConnection({
host: process.env.rds_host,
user: process.env.rds_username,
password: process.env.rds_password,
port: process.env.rds_port // is your port the same as your localhost?
// include your database name here
});
// I suggest you to await your client connection
// since mysql executes sequentially, not asynchronously
client.connect(function(err) => {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log("Connected!");
});
}
如果錯誤仍然存在,則意味着您的環境變量設置不正確,因此應檢查您的數據庫配置(請參閱內聯注釋)。
問題是 >> 代碼沒有等待完成 Promise
您可以通過以下方式解決:
然后添加回調
Promise.all(array).then(result => {
console.log(result);
callback(null, {});
});
或者
使用等待
let result = await Promise.all(promiseArray);
console.log(result)
callback(null, {});
注意:使用 try-catch 處理等待中的錯誤
另外,不要使用map
來循環數組,而是使用For loop
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.