ajax-promise.js 518 B

123456789101112131415161718192021
  1. function ajax(url) {
  2. return new Promise((resolve, reject) => {
  3. const xhr = new XMLHttpRequest()
  4. xhr.open('GET', url, true)
  5. xhr.onreadystatechange = function () {
  6. if(xhr.readyState === 4) {
  7. if(xhr.status === 200) {
  8. resolve(JSON.parse(xhr.responseText))
  9. }else if(xhr.status === 404){
  10. reject(new Error('404 not found'))
  11. }
  12. }
  13. }
  14. xhr.send()
  15. })
  16. }
  17. const url = '/data/test.json'
  18. ajax(url)
  19. .then(res=>console.log(res))
  20. .catch(err=>console.log(err))