[英]JavaScript, Node.JS : unable to update a variable in a loop
我正在通過 Node.js 構建 API。
我有一個將值添加到最初為空的數組的循環,但該數組保持為空。 以下是我的代碼。
get_doc_name = async (event) => {
const connection = await db.connection()
try {
const doc_ids = event.doc_ids
// array that has JSONs as element
// e.g. [ {1 : 'certificate.pdf'}, {2: 'report.jpeg'}]
let dict = []
await doc_ids.map(async function(id) {
const sql = "SELECT link FROM document WHERE id=?"
await connection.query(sql, id, async function (err, result) {
if (err) throw err
const link = await result[0].link
const doc_name = await link.split('/').pop()
await dict.push({
key: id,
value: doc_name
})
console.log(dict)
})
})
return dict
} catch (err) {
console.log(err.message)
} finally {
connection.end()
console.log('MySQL connection closed')
}
}
該函數返回一個空數組。 但是,它會在執行console.log(dict)
時打印更新的數組。 我需要函數來返回更新后的數組。
此外,當函數被調用時,'finally' 語句中的代碼在'try' 語句中的代碼之前執行。 該程序在打印dict
之前打印MySQL connection closed
。
任何幫助表示高度贊賞!
當您從 DB 檢索數據時,最好使用串行 Promise 而不是並行 Promise 從 DB 獲取數據。 我的做法是在串行 Promise 中。
使用SELECT link FROM document WHERE id in ()
而不是id=
在您的 SQL 中獲取數據是更好的做法,因為在您的情況下您不需要對數據庫進行多次 I/O。
但是,我沒有改變這部分邏輯。
此外,您應該承諾您的connection.query
並從中返回一個值。 我在getResult()
函數中創建它。
get_doc_name = async event => {
try {
const connection = await db.connection();
try {
const doc_ids = event.doc_ids;
// array that has JSONs as element
// e.g. [ {1 : 'certificate.pdf'}, {2: 'report.jpeg'}]
let dict = [];
//Promises in serial here
for (const id of doc_ids) {
const result = await getResult(connection, id);
dict.push(result);
}
console.log(dict);
return dict;
} catch (err) {
console.log(err);
} finally {
await connection.end();
console.log("MySQL connection closed");
}
} catch (err) {
console.log(err);
}
};
function getResult(connection, id) {
return new Promise((resolve, reject) => {
const sql = "SELECT link FROM document WHERE id=?";
connection.query(sql, id, function (err, result) {
if (err) reject(err);
const link = result[0].link;
const doc_name = link.split("/").pop();
resolve({ key: id, value: doc_name });
});
});
}
get_doc_name()
.then(dict => console.log(dict))
.catch(console.log);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.