Last active
February 26, 2017 00:59
-
-
Save kenmori/91a61e168f90fe311c4d35219b236aca to your computer and use it in GitHub Desktop.
promise
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
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