Skip to content

Instantly share code, notes, and snippets.

@numberoverzero
Last active December 8, 2016 06:22
Show Gist options
  • Save numberoverzero/5ae855abc7d4382bc96c52717d501030 to your computer and use it in GitHub Desktop.
Save numberoverzero/5ae855abc7d4382bc96c52717d501030 to your computer and use it in GitHub Desktop.
micro ajax 'library' wrapping XMLHttpRequest in a Promise. 315 bytes before compression.
/*
Usage ::
const url = "http://httpbin.org/post",
body = JSON.stringify({foo: "bar"}),
timeout = 5000; // 5 seconds
rq(url, {m:"POST", b:body, t:timeout})
.then(xhr => console.log(xhr.response))
.catch(xhr => console.log("Failed to load " + url));
*/
/*
u :: "https://google.com" // url **required**
opts :: {
m: "GET", // method (defaults to GET)
h: {"content-length": "3"}, // headers (defaults to none)
r: "json", // responseType (defaults to json)
t: 5000, // timeout (ms) (defaults to unlimited)
b: {userId: "foo"}, // body (defaults to undefined)
}
x :: reserved
*/
rq = (u, opts, x) => {
x = new XMLHttpRequest;
x.open(opts.m || "GET", u);
x.responseType = opts.r || "";
x.timeout = opts.t || 0;
Object.keys(opts.h || 0).forEach(h => x.setRequestHeader(h, opts.h[h]));
return new Promise((y,n) => {
x.onreadystatechange = _=>{
x.readyState==4 && [n,y][(!!x.response && (x.status/200|0)==1)|0](x);
};
x.ontimeout = _=>n(x);
x.send(opts.b || undefined);
})
};
rq=(c,b,a)=>{a=new XMLHttpRequest;a.open(b.m||"GET",c);a.responseType=b.r||"";a.timeout=b.t||0;Object.keys(b.h||0).forEach(c=>a.setRequestHeader(c,b.h[c]));return new Promise((c,d)=>{a.onreadystatechange=b=>{4==a.readyState&&[d,c][(!!a.response&&1==(a.status/200|0))|0](a)};a.ontimeout=b=>d(a);a.send(b.b||[]._)})};
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2016 Joe Cross
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment