我试图将 Knexjs 的选择查询结果归因于一个变量。 我的代码是这样的:
function getAllCategories() {
let categories;
categories = database.from("categories").select("category").then(function (rows) {
for (let row of rows) {
console.log(row)
}
});
console.log(categories)
}
当我调用该函数时: .然后在终端上写入如下所示的对象数组:
{ category: 'Pasticceria' }
{ category: 'Salati' }
...
如果我console.log(categories);在终端上打印:
Promise [Object] {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined
}
如何赋予变量能够循环它? 非常感谢大家的帮助,我已经好几天了。
最佳答案
getAllCategories 返回 promise ,这就是您调用该函数时所看到的。最简单的方法是将调用 getAllCategories 的任何代码 package 在异步函数中,然后等待 getAllCategories 的值。我假设您希望 getAllCategories 返回类别,因此它可能看起来像这样:
async function wrapper() {
async function getAllCategories() {
return database.from("categories").select("category")
};
const categories = await getAllCategories()
// do whatever you want to do with categories
}
您可以阅读有关 async/await 语法 here
关于javascript - 将 knex 的查询结果传递给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716394/