将 knex 的查询结果传递给变量
Pass to a Variable a query result of knex
我试图将使用 Knexjs 的 select 查询的结果归因于一个变量。
我的代码是这样的:
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(类别);在终端上打印:
Promise [Object] {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined
}
我怎样才能赋予一个变量以循环它?
非常感谢大家的帮助,这几天一直在敲脑袋
getAllCategories returns a promise,这就是您在调用该函数时看到的内容。最简单的做法是将任何调用 getAllCategories 的代码包装在异步函数中,然后等待 getAllCategories 的值。我假设您希望 getAllCategories return 类别,所以它可能看起来像这样:
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
正如 Adam tropp 现在提到的类别 return 需要执行的承诺,当您调用 .then() 方法时,它会在后台调用 exec() 方法,就像您使用 async/await 当您使用 await it return 应该在 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
getAllCategories() 方法 Adam 做出了 return 一个承诺,你可以将任何你想要的链接到它,它只会在你调用 .then() 方法或使用我 kenda 更喜欢的 await 时执行.
我试图将使用 Knexjs 的 select 查询的结果归因于一个变量。 我的代码是这样的:
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(类别);在终端上打印:
Promise [Object] {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined
}
我怎样才能赋予一个变量以循环它? 非常感谢大家的帮助,这几天一直在敲脑袋
getAllCategories returns a promise,这就是您在调用该函数时看到的内容。最简单的做法是将任何调用 getAllCategories 的代码包装在异步函数中,然后等待 getAllCategories 的值。我假设您希望 getAllCategories return 类别,所以它可能看起来像这样:
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
正如 Adam tropp 现在提到的类别 return 需要执行的承诺,当您调用 .then() 方法时,它会在后台调用 exec() 方法,就像您使用 async/await 当您使用 await it return 应该在 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
getAllCategories() 方法 Adam 做出了 return 一个承诺,你可以将任何你想要的链接到它,它只会在你调用 .then() 方法或使用我 kenda 更喜欢的 await 时执行.