简体   繁体   中英

Creating a API factory like angular using pure XHR

Hi I am trying to build a single JavaScript file which handles all the API requests for me. Then use this file to make all the XHR request. As the XHR is async the function would return before the onreadystatechange gets executed. I tried something show below but its not working can someone tell me how to achieve this ?

 var apiFactory={}; var Req = new XMLHttpRequest(); apiFactory.sendRequest=function(URL,type,params) { Req.open("GET", "<get url>", true); Req.send(); return Req.onreadystatechange = function () { if (Req.readyState == 4 && Req.status == 200) { console.log( JSON.parse(Req.responseText)); return JSON.parse(Req.responseText); } }; }; module.exports=apiFactory; 

You can use ES6 promises:

 var apiFactory={}; apiFactory.sendRequest=function(URL,type,params) { return new Promise(function(resolve, reject) { var Req = new XMLHttpRequest(); Req.open("GET", URL, true); Req.send(); return Req.onreadystatechange = function () { if (Req.readyState == 4 && Req.status == 200) { console.log( JSON.parse(Req.responseText)); resolve(JSON.parse(Req.responseText)); } }; }); }; apiFactory.sendRequest('https://ghibliapi.herokuapp.com/films/58611129-2dbc-4a81-a72f-77ddfc1b1b49').then((res)=>{ console.log('result:',res) }) //module.exports=apiFactory; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM