Skip to content

Instantly share code, notes, and snippets.

@jw-jenrise
Last active February 13, 2018 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jw-jenrise/b48f20a0802e28df7070d7c08994842d to your computer and use it in GitHub Desktop.
Save jw-jenrise/b48f20a0802e28df7070d7c08994842d to your computer and use it in GitHub Desktop.
function getPromiseRemoteData(url){
var promiseRemoteData = new Promise(function(resolve,reject){
// Initiate call
//var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; //Uncomment this line if you are using it in node js environment.
// 1. Create the request
var xhr = new XMLHttpRequest();
// 2. Create the URL
var delay = Math.floor(Math.random() * 9) + 1;
// Open the URL
xhr.open("GET", url + "?delay="+delay, true);
// Specify what should be done after the remote call
xhr.onload = function(){
var remoteResponseText = xhr.responseText;
var remoteObject = JSON.parse(remoteResponseText)
remoteObject.isValid = function(){
return this.hasOwnProperty('data');
}
if (remoteObject.isValid()){
resolve (remoteObject); // THIS SHOULD RETURN DATA
} else {
reject("Invalid record");
}
};
xhr.send();
});
return promiseRemoteData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment