【发布时间】:2021-03-05 00:20:41
【问题描述】:
我今天有一个小问题。我还发现了类似的主题,不幸的是这对我没有帮助。
我想用 Knex 加载数据并进一步使用它。在 then 函数的第一个日志console.log(channel['name']) 中,我得到了想要的名称,但在最后一个控制台日志console.log(channel); 中,我只收到消息Promise { <pending> }。
使用 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