JS promise : wrapping XMLHttpRequest in Promise


/ Published in: JavaScript
Save to your folder(s)

wrapping XMLHttpRequest in Promise


Copy this code and paste it in your HTML
  1. function callget(url){
  2. return new Promise(function(resolve,reject){
  3. var oReq = new XMLHttpRequest();
  4. oReq.open("GET", url);
  5. oReq.onload = function(){
  6. if(oReq.status ==200){
  7. resolve(oReq.response);
  8. }
  9. else{
  10. reject(oReq.statusText);
  11. }
  12. };
  13. oReq.error = function(){
  14. reject('Network error');
  15. };
  16. oReq.send();
  17.  
  18. });
  19. }
  20.  
  21.  
  22.  
  23. var jq = 'https://code.jquery.com/jquery-33.2.1.min.js';
  24. callget(jq).then(finish).catch(finish);
  25.  
  26. function finish(x){
  27. console.log(x);
  28. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.