-2

I have a small question today. I also found similar topics, which unfortunately did not help me. I want to load data with Knex and use it further. In the first log console.log(channel['name']) in the then function I get the name as wanted, but in the last console log console.log(channel); I only get the message Promise { <pending> }. What is the easiest way to use Node.js & Knex.js to get data in this way and use it further?

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);
Norman Huth
  • 519
  • 5
  • 16
  • So from the first page nothing works. @jonrsharpe – Norman Huth Mar 05 '21 at 00:48
  • You *must* move the `console.log` call inside the `then` callback, there's no way around that. You have to wait for the asynchronous result one way or another, it simply won't be available immediately. – Bergi Mar 05 '21 at 02:01
  • But I need the data later. How can I wait for asynchronous? @Bergi – Norman Huth Mar 05 '21 at 02:15
  • What do you mean by "later"? Put all the code that should run *later* (when the channel data has been loaded) inside the `then` callback - that's how promises work. – Bergi Mar 05 '21 at 02:19
  • For example: I put let ´name = channel['name']´ in the ´then´ function, because need the name in the rest oft the script, but name is always ´undefined´ in the rest of the script. – Norman Huth Mar 05 '21 at 02:25

1 Answers1

0

This package helped with my problem: https://www.npmjs.com/package/sync-mysql

Norman Huth
  • 519
  • 5
  • 16