0
我有一个函数可以进行数据库查询,然后需要返回结果。在返回值之前等待内部函数完成
查询是使用Node.js到mysql数据库,结果然后返回到询问者(NPM模块)提示。
如果这是前端问题,我会使用jquery的内置承诺:(示例)。 $ .ajax.done()。然而,mysql NPM软件包并没有内置query()方法的promise。
// OPTION 1, wait for query to complete before returning choicesArray (this example returns an empty array)
choices() {
let choicesArray = [];
connection.query(`SELECT * FROM products`, (err, res)=>{
for (item of res) {
choicesArray.push(`${item.product} | ${item.price}`);
};
});
// wait here for query to complete
return choicesArray;
}
// OPTION 2, change the syntax to take advantage of the query callback, something more like below (this example does not return the choicesArray all the way to the enclosing function)
choices() {
connection.query(`SELECT * FROM products`, (err, res)=>{
let choicesArray = [];
for (item of res) {
choicesArray.push(`${item.product} | ${item.price}`);
};
return choicesArray;
});
} // (node:3877) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: You must provide a `choices` parameter
(如果你使用的节点或异步),你应该使用一个承诺或回调。 – Andy
@Quentin为前端ajax调用提供了一个很好的资源:https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call。我认为这个问题有很大的不同,需要具体的答案。你会否将这个标记为重复? – Gerard
这不是一个前端Ajax调用并不重要。这是一个异步调用,解决方案是相同的。 – Quentin