繁体   English   中英

Nodejs 异步/等待未按预期工作

[英]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);
})

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

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

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

您不会从getQuotes() function 返回任何内容。回调中的返回只会从回调返回,而不是从封闭的 function 返回。您也不会在任何地方等待,这意味着您的异步 function 不会实际等待您的查询结果。

从我的角度来看,最好不要混淆awaitthen 要么使用一个或另一个。
我建议使用await给 go。

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

问题是您需要从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 function 应该返回这样的结果。

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM