abstracted async

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

19
bot.js
View File

@@ -101,7 +101,7 @@ function noQuestion() {
// 3. RedditBooru // 3. RedditBooru
function bestEffortRequest(subpage, page_max) { 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; } if(reddit_response) { return reddit_response; }
let imgur_response; let imgur_response;
@@ -147,13 +147,8 @@ function imgurRequest(subreddit, page_max) {
return returnText; return returnText;
} }
// Dalton async reddit? // Abstracted Reddit Json media grab.
function asyncRedditRequest(requested_item) { function handleRedditJson(data) {
let url= "https://www.reddit.com/r/" + requested_item + "/.json?show=all&count=25&limit=100";
fetch(url)
.then(data => {
let json = data.json(); let json = data.json();
for(i = 0; i < json.data.children.length; i++) { for(i = 0; i < json.data.children.length; i++) {
let rand = getRandomInt(0, json.data.children.length - 1); let rand = getRandomInt(0, json.data.children.length - 1);
@@ -162,7 +157,13 @@ function asyncRedditRequest(requested_item) {
return json.data.children[rand].data.url; 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 => {return process(data);})
.catch(error => { .catch(error => {
client.channels.get('357365312620068874').send(error.message); client.channels.get('357365312620068874').send(error.message);
return ""; }) return ""; })