[英]Trying to set global variable inside a callback nested in forEach loop
I am working with the Twitter API and I am trying to create a thread.我正在使用 Twitter API,并且正在尝试创建一个线程。 To make a thread, you have to reply to your latest reply to continue the thread, not the original Tweet.要创建话题,您必须回复最新回复才能继续话题,而不是原始推文。 To do this, you have to get the tweet id to use for in_reply_to_status_id
paramater.为此,您必须获取用于in_reply_to_status_id
参数的推文 ID。
The tweet id is accessible in the callback function, where I try to set the global variable tweetId
.推文 ID 可以在回调函数中访问,我尝试设置全局变量tweetId
。 The problem is that the tweet id isn't updating, and all of the replies just go to the same tweet id.问题是推文 id 没有更新,所有回复都转到同一个推文 id。
Here is my code.这是我的代码。
let tweetId;
if (tweets.length > 1) {
// tweet original tweet
client.post(
"statuses/update",
{ status: tweets[0] },
(error, tweet, response) => {
if (error) return res.status(500).send("Server Error");
// set tweet id of original tweet to be used for reply
tweetId = tweet.id_str;
// loop through all tweets and reply to the latest reply (Creating a thread)
tweets
.filter((tweet, i) => i > 0)
.forEach((tweet) => {
client.post(
"statuses/update",
{ status: tweet, in_reply_to_status_id: tweetId },
(error, tweet, response) => {
if (error) return res.status(500).send("Server Error");
// set new tweet id to be used for reply
tweetId = tweet.id_str;
}
);
});
}
);
res.send("success");
}
globalThis.tweetId = tweet.id_str;
let 只会在相同的范围内保持它的价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.