JavaScript,节点.JS:无法更新循环中的变量



我正在通过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

非常感谢您的帮助!

当您从数据库中检索数据时,最好使用串行Promise而不是并行Promise从数据库中获取数据。我的做法是在连续剧《承诺》中。

在SQL中使用SELECT link FROM document WHERE id in ()而不是id=获取数据是一种更好的做法,因为在您的情况下不需要对数据库进行多次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);

最新更新