promise
by rana777
JavaScript
var url = "https://davids-restaurant.herokuapp.com/categories.json";
function get(url){
//return a new promise
return new Promise(function(resolve,reject){
var req = new XMLHttpRequest();
req.open('GET',url);
req.onload = function(){
if(req.status==200){
//resolve the promise with the response text
resolve(req.response);
}else{
reject(Error(req.statusText));
}
};
//Handle network errors
req.onerror = function(){
reject(Error('Network Error!!!!'))
};
//Make the request
req.send();
});
}
//use it!
get(url).then(function(response){
console.log("Success!",response);
},function(error){
console.error("Failed!!",error)
})