尝试使用 Twitter 获取批量推文时如何修复无限循环

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

我正在使用 Twit npm 包从用户时间线检索推文。获取多批推文的方法是您必须将 max_id 的参数更改为 Twitter API。我只是在测试让我的 while 循环工作,但它是无限的,因为我不知道如何等待 get 函数完成。

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);
        }
    });
}

我从来没有点击过控制台日志,因为它返回到循环的顶部再次检查条件,而条件永远不会改变,从而导致无限循环。我该如何解决这个问题,以便 get 函数在再次检查条件之前完成?

尝试使用 async/await 语法

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);
    }
 }

}