【问题标题】:Simple Output with Node.js and Knex.js Promise { <pending> } [duplicate]使用 Node.js 和 Knex.js Promise { <pending> } [重复] 的简单输出
【发布时间】:2021-03-05 00:20:41
【问题描述】:

我今天有一个小问题。我还发现了类似的主题,不幸的是这对我没有帮助。 我想用 Knex 加载数据并进一步使用它。在 then 函数的第一个日志console.log(channel['name']) 中,我得到了想要的名称,但在最后一个控制台日志console.log(channel); 中,我只收到消息Promise { &lt;pending&gt; }。 使用 Node.js & Knex.js 以这种方式获取数据并进一步使用的最简单的方法是什么?

let channel = knex("channels").where({
    twitch_id: twitchID
}).first().then(function (channel) {
    if (channel) {
        console.log(channel['name'])
        return channel;
    }
}).catch(function (error) {
    console.log(error);
});

console.log(channel);

【问题讨论】:

  • 所以从第一页开始没有任何效果。 @jonrsharpe
  • 必须then回调中移动console.log调用,这是没有办法的。您必须以一种或另一种方式等待异步结果,它根本不会立即可用。
  • 但我稍后需要数据。如何等待异步? @Bergi
  • “稍后”是什么意思?将所有应该稍后(当频道数据加载后)运行的代码放在then 回调中——这就是promise 的工作方式。
  • 例如:我把 let ´name = channel['name']´ 放在 ´then´ 函数中,因为在脚本的其余部分需要 name,但 name 在脚本的其余部分。

标签: javascript node.js knex.js


【解决方案1】:

这个包帮助解决了我的问题: https://www.npmjs.com/package/sync-mysql

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2021-04-21
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    相关资源
    最近更新 更多