abstracted async

This commit is contained in:
Dalton
2018-12-07 18:31:46 -08:00
parent b680e8bc7f
commit 561d4d5452

29
bot.js
View File

@@ -101,7 +101,7 @@ function noQuestion() {
// 3. RedditBooru
function bestEffortRequest(subpage, page_max) {
let reddit_response = asyncRedditRequest(subpage);
let reddit_response = asyncSiteRequest("https://www.reddit.com/r/" + subpage + "/.json?show=all&count=25&limit=100", handleRedditJson);
if(reddit_response) { return reddit_response; }
let imgur_response;
@@ -147,22 +147,23 @@ function imgurRequest(subreddit, page_max) {
return returnText;
}
// Dalton async reddit?
function asyncRedditRequest(requested_item) {
// Abstracted Reddit Json media grab.
function handleRedditJson(data) {
let json = data.json();
for(i = 0; i < json.data.children.length; i++) {
let rand = getRandomInt(0, json.data.children.length - 1);
let url= "https://www.reddit.com/r/" + requested_item + "/.json?show=all&count=25&limit=100";
if (json.data.children[rand].data.post_hint === "image" || json.data.children[rand].data.post_hint === "link" || json.data.children.data.post_hint === "rich:video") {
return json.data.children[rand].data.url;
}
}
}
// Makes an async url request with the provided function: 'process'.
function asyncSiteRequest(url, process) {
fetch(url)
.then(data => {
let json = data.json();
for(i = 0; i < json.data.children.length; i++) {
let rand = getRandomInt(0, json.data.children.length - 1);
if (json.data.children[rand].data.post_hint === "image" || json.data.children[rand].data.post_hint === "link" || json.data.children.data.post_hint === "rich:video") {
return json.data.children[rand].data.url;
}
}
})
.then(data => {return process(data);})
.catch(error => {
client.channels.get('357365312620068874').send(error.message);
return ""; })