Skip to content

Instantly share code, notes, and snippets.

@ryanlid
Created August 9, 2019 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanlid/7915621e9dc1e7fec3505001d8cb8a60 to your computer and use it in GitHub Desktop.
Save ryanlid/7915621e9dc1e7fec3505001d8cb8a60 to your computer and use it in GitHub Desktop.
promise ajax
function ajax(method, url, data) {
var request = new XMLHttpRequest();
return new Promise(function (resolve, reject) {
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
resolve(request.responseText);
} else {
reject(reject(reject.status));
}
}
};
request.open(method, url);
request.send(data);
});
}
var p = ajax("GET", "https://jsonplaceholder.typicode.com/todos/1");
p.then(function (text) {
console.log("text", text);
return text;
})
.then(function (text2) {
console.log("text2:", text2);
return ajax("GET", "https://jsonplaceholder.typicode.com/todos/2");
})
.then(function (text3) {
console.log("text3", text3);
})
.catch(function (status) {
console.log(status);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment