laneherby
laneherby

Reputation: 485

How to fix infinite while loop when trying to get batch of tweets using Twit

I'm using the Twit npm package to retrieve tweets from a user timeline. The way to get multiple batches of tweets is you have to change max_id of parameters to Twitter API. I'm just testing to get my while loop to work but it is infinite because I don't know how to wait for get function to finish.

const twitParams = {
        screen_name: username,
        exclude_replies: false,
        include_rts: false,
        trim_user: true,
        count: 200
    };

const allTweetsText = [];

while (allTweetsText.length <= 500) {
    twitClient.get("statuses/user_timeline", twitParams, (error, tweets, res) => {
        for (tweet of tweets) {
            allTweetsText.push(tweet.text);
            console.log(allTweetsText.length);
        }
    });
}

I never hit the console log becuase it goes back to the top of the loop to check the condition again which never changes resulting in an infinite loop. How can I fix this so the get function finishes before checking the condition again?

Upvotes: 1

Views: 95

Answers (1)

omer727
omer727

Reputation: 7565

try using async/await syntax

async function(){
const twitParams = {
        screen_name: username,
        exclude_replies: false,
        include_rts: false,
        trim_user: true,
        count: 200
};

const allTweetsText = [];

while (allTweetsText.length <= 500) {
    const tweets = await twitClient.get("statuses/user_timeline", twitParams);
    
    for (tweet of tweets) {
        allTweetsText.push(tweet.text);
        console.log(allTweetsText.length);
    }
 }

}

Upvotes: 1

Related Questions