Last active
October 29, 2017 00:54
-
-
Save kra3/00ce929296b98b34db73e76ee5c85246 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// no way to reset, at the moment | |
const get = (() =>{ | |
let counter = 0; | |
return (url) => { | |
return new Promise((resolve, reject) => { | |
if(counter > 100) { | |
reject(false); | |
} | |
counter++; | |
let request = new XMLHttpRequest(); | |
request.open("GET", url); | |
request.onload = function () { | |
if (this.status >= 200 && this.status < 300) { | |
resolve(request.response); | |
} else { | |
reject({ | |
status: this.status, | |
statusText: request.statusText | |
}); | |
} | |
}; | |
request.onerror = function () { | |
reject({ | |
status: this.status, | |
statusText: request.statusText | |
}); | |
}; | |
request.send(); | |
}); | |
} | |
})(); | |
const solve = (url, requiredResultCount) => { | |
return new Promise((resolve, reject) => { | |
const messages = new Set(); | |
const again = () => setTimeout(() => { | |
get(url) | |
.then(res => messages.add(res)) | |
.catch(console.warn) | |
.then(() => { | |
if (messages.size !== requiredResultCount) { | |
again(); | |
} else { | |
resolve(Array.from(messages)); | |
} | |
}); | |
}, 0); | |
again(); | |
}); | |
} | |
const API = 'https://api.github.com/zen'; | |
console.log(solve(API, 3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment