Last active
December 9, 2019 10:17
-
-
Save oneshubh/cef438b573b708b5f126e1a5fc89cab0 to your computer and use it in GitHub Desktop.
Call multiple API synchronously and get all results or failure
This file contains hidden or 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
| // author : oneshubh | |
| function retry(api,numberOfTries){ | |
| var counter = numberOfTries; | |
| console.log("counter initially is",counter); | |
| var results = [] | |
| var getRandom = function(){ | |
| counter--; | |
| console.log("counter is",counter); | |
| return fetch('https://randomuser.me/api/',{ headers: { | |
| "Content-Type": "application/json", | |
| // "Content-Type": "application/x-www-form-urlencoded", | |
| }}) | |
| .then(function(response) { | |
| return response.json(); | |
| }).then(function(response) { | |
| // console.log("response is",response); | |
| results.push(response); | |
| if(counter == 0){ | |
| return results; | |
| }else{ | |
| return getRandom(); | |
| } | |
| ; | |
| }) | |
| .catch(function(err){ | |
| results.push(err); | |
| if(counter == 0){ | |
| return results; | |
| }else{ | |
| return getRandom(); | |
| } | |
| console.log("error is",err); | |
| }) | |
| } | |
| return getRandom() | |
| } | |
| var call = retry("api",5); | |
| call.then(function(result){ | |
| console.log("Result length is",result.length); | |
| console.log("result is",result) | |
| }).catch(function(err){ | |
| console.log("Error is",err); | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment