Nodejs async/await 未按预期工作

Nodejs async/await not working as expected

我有一个 express API 可以从我的动物数据库中读取数据。我有一个名为 Database 的 class 设置,它处理我所有的动物群查询,还有一个名为 getQuotes 的异步方法,它基本上获取动物群文件,一般结构是这样的:

async getQuotes() {
    // note, `query` is an async function
    const doc = this.client.query(...).then((res) => {
        const data = ...; // to keep this short I'm not gonna show this
        console.log("faunadb handler: " + data); // just for debug
        return Promise.resolve(data);
    })
}

然后当我启动 express API 时,我让它调用 getQuotes 方法并记录数据(仅用于调试)。

const quotes = db.getQuotes().then((quotes) => {
    console.log("fauna consumer: " + quotes);
})

现在,当我 运行 应用程序时,我得到以下输出:

starting server on port.... ussual stuff
fauna consumer: undefined
faunadb handler: { ... }

在我们实际从动物群查询 API 中获得承诺之前,动物群消费者代码 运行s。我需要使用 .then 因为节点出于某种原因不允许我使用等待。有谁知道如何解决这个问题?谢谢! (在 Arch Linux 上使用节点版本 v16.14.0,运行ning)

您没有return从您的getQuotes()函数中获取任何东西。回调中的 return 只会从回调中转到 return,而不是从封闭函数中转到 return。您也不会在任何地方等待,这意味着您的异步函数不会实际等待您的查询结果。

在我看来,最好不要混淆 awaitthen。要么使用一个,要么使用另一个。
我建议使用 await.

async getQuotes() {
    // note, `query` is an async function
    const res = await this.client.query(...)
    const doc = ...; // to keep this short I'm not gonna show this
    console.log("faunadb handler: " + doc); // just for debug
    return doc;
}

尝试使用await

async getQuotes() {
    const res = await this.client.query(...);
    const data = ...;
    console.log("faunadb handler: " + data); // just for debug
    return data;
}
// must be in async function
const quotes = await db.getQuotes();
console.log("fauna consumer: " + quotes);

问题是您需要return来自getQuotes的数据,请将代码更改如下(替换占位符):

  async getQuotes() {
    // note, `query` is an async function
    const res = await this.client.query(...)
    const data = ...; // to keep this short I'm not gonna show this
    console.log("faunadb handler: " + data); // just for debug
    return data
  }

getQuotes 函数应该 return 这样的结果。

async getQuotes() {
    // note, `query` is an async function
    return this.client.query(...).then((res) => {
        const data = ...; // to keep this short I'm not gonna show this
        console.log("faunadb handler: " + data); // just for debug
        return Promise.resolve(data);
    })
}

async getQuotes() {
    // note, `query` is an async function
    const doc = await this.client.query(...);
    const data = ...; // to keep this short I'm not gonna show this
    console.log("faunadb handler: " + data); // just for debug
    return Promise.resolve(data);
}