簡體   English   中英

將 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)

}

當我調用 function: 時,然后在終端上寫下這樣的對象數組:

{ category: 'Pasticceria' }
{ category: 'Salati' }
...

相反,如果我 console.log(categories); 在終端上打印:

    Promise [Object] {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined
}

我如何將其歸因於變量以使其能夠循環? 非常感謝大家的幫助,我這幾天一直在敲頭。

getAllCategories 返回promise ,這是您在調用 function 時看到的。 最簡單的做法是將調用 getAllCategories 的任何代碼包裝在異步 function 中,然后等待 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 語法的信息

正如 Adam tropp 提到的,類別現在返回需要執行的 promise,當您調用 .then() 方法時,它會在后台調用 exec() 方法,就像您在使用 await 時使用 async/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() 方法返回一個 promise,您可以將其鏈接到任何您想要的東西,並且它只會在您調用 .then() 方法或使用我 kenda 更喜歡的 await 時執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM