Skip to content

Instantly share code, notes, and snippets.

@kenmori
Last active February 26, 2017 00:59
Show Gist options
  • Save kenmori/91a61e168f90fe311c4d35219b236aca to your computer and use it in GitHub Desktop.
Save kenmori/91a61e168f90fe311c4d35219b236aca to your computer and use it in GitHub Desktop.
promise
var promise = function(url) {
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function () {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function () {
reject(Error("Nettwork Error"))
};
req.send();
});
}
promise('http://localhost:3000/posts').then(function(result){
var res = document.querySelector('#result')
var fragment = document.createDocumentFragment();
JSON.parse(result).slice().forEach(function(ele, i){
var li = document.createElement('li');
li.textContent += ele.comments;
fragment.appendChild(li);
});
res.appendChild(fragment);
}, function(reject){
console.log(reject);
}).catch(function(error){
console.log(error);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment