Ad

Console.log Showing Up At The End Of The Function

- 1 answer

I'm trying to make a little Twitter bot with JavaScript and Node.JS. But, in a function, all my console.log are showing up at the end.

I've tried with async, callback and classic function but I always get the same output.

    getTweets: function(Twitter, callback) {
        Twitter.get(`search/tweets`, this.parameters, callback);
    },

    likeTweet: function(Twitter, tweetid, callback) {
        Twitter.post(`favorites/create`, { id:tweetid }, callback);
    },

    execute: function(Twitter) {

        let count = 0;
        let done = 0;

        this.getTweets(Twitter, (err, tweets) => {

            for (thetweet of tweets.statuses) {

                if (typeof thetweet === `undefined`) {
                    continue;
                }

                count++;

                this.likeTweet(Twitter, thetweet.id_str, (err, reponse) => {

                    if (err) {
                        switch (err.code) {
                            case 139: console.log(`Tweet ${count}:`.bold.yellow + ` Le tweet a déjà été aimé par le bot.`); break;
                            default: console.log(`Tweet ${count}:`.bold.red + ` Erreur inconnue => ${err}`); break;
                        }
                    } else {
                        console.log(`Tweet ${count}:`.bold.green + ` Tweet aimé`);
                        done++;
                    }
                });
            }
        });
    }

Before I call execute(), I have a console.log(1). After execute(), there is an another console.log(3). And in execute(), there are console.log() that show a text. (Yeah I know, there is a lot of console.log)

I would like to have that:

1

Tweet 1: text

Tweet 2: text

Tweet 3: text

...

3

But, when I run bot.js, I'm getting this:

1

3

Tweet 15: text

Tweet 15: text

Tweet 15: text

...

I'm pretty sure that the problem is easy to spot but I don't know how to do. I hope I'm clear enough and I don't make to many mistakes with my message.

Ad

Answer

await will work only on Promises, not on callback functions. await waits for the Promise to fulfill.

You can use any Promise library to make Twitter callback functions as promise and use await against them. I would prefer bluebird.

import {Promise} from 'bluebird'
import {Twitter} from 'twitter'
Promise.promisifyAll(Twitter);

Now you could use await and make it look like synchronous code.

let tweets = await Twitter.get(`search/tweets`,parameters);
Ad
source: stackoverflow.com
Ad