Posted By

sudhiakki on 07/23/17


Tagged

promise


Versions (?)

JS promise : wrapping XMLHttpRequest in Promise


 / Published in: JavaScript
 

wrapping XMLHttpRequest in Promise

  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  

You need to login to post a comment.