我试图将使用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
}
如何赋予变量变量以使其循环? 非常感谢大家的帮助,我已经好几天没碰头了。
答案 0 :(得分:2)
getAllCategories返回一个promise,这是调用函数时看到的。最简单的方法是将调用getAllCategories的代码包装在异步函数中,然后等待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
}
您可以了解异步/等待语法here
答案 1 :(得分:0)
正如Adam tropp提到的那样,类别现在返回一个需要执行的承诺,当您调用.then()方法时,它将在后台调用exec()方法,就像您在使用async / await时一样使用await,它返回应该在then块中抛出的结果。 这也使您可以在查询中链接
async function getAllCategories() {
return database.from("categories").select("category")
};
const categories = await getAllCategories().where('id', '=', 1)
// do whatever you want to do with categories
Adam做出的getAllCategories()方法返回一个承诺,即您可以链接任何想要的对象,并且只有在您调用.then()方法或使用了我肯达所偏爱的等待时,它才会执行。