我制作了一个Twitter机器人,该机器人从reddit上获取帖子并定期发推文。我检查“是重复的帖子”控件,因此我将每个帖子写入.txt文件并逐行阅读。
我希望while循环等待直到完成(while(0))中断,但是我测试了我的代码,并且一直都发送相同的链接。但是while循环再次运行5-6次,然后继续进行并下载了重复的图片。
如何等待直到循环完全结束?
getImage: async function () {
var selectedSubreddit = await subreddit.randomSubreddit();
var imageURL;
//getting the image URL to download later
imageURL = await urlGetter(subreddit);
while (imageURL === '-1' || table.checkImage(imageURL[0]) === 1) {
imageURL = await urlGetter(selectedSubreddit);
}
const downloadOptions = {
url: imageURL[0],
dest: `./images/x.jpg`
};
try {
const { filename, image } = await downloader.image(downloadOptions);
console.log(' -> Image downloaded!');
} catch (e) {
console.log(' -> Image download failed');
process.exit();
}
}
-urlGetter函数
const getURL = function (subreddit) {
return new Promise((resolve, reject) => {
fetch(`https://www.reddit.com/r/${subreddit}/random.json?limit=1`)
.then(res => res.json())
.then(json => {
let image;
let oldImage;
let crossParent;
let permalink;
try {
image = json[0].data.children[0].data.url;
crossParent = json[0].data.children[0].data.crosspost_parent;
permalink = json[0].data.children[0].data.permalink;
title = json[0].data.children[0].data.title;
} catch (error) {
image = json.data.children[0].data.url;
crossParent = json.data.children[0].data.crosspost_parent;
permalink = json[0].data.children[0].data.permalink;
title = json[0].data.children[0].data.title;
}
if (!image) return resolve('-1');
if (crossParent) return resolve('-1');
let extension = image.substring(
image.lastIndexOf('.') + 1,
image.lastIndexOf('.') + 4
);
if (extension != 'jpg' && extension != 'png') return resolve('-1');
return resolve([image, permalink, title]);
})
.catch(err => {
return resolve('-1');
});
});
};