Created
January 27, 2016 12:56
-
-
Save fabiodan/0ba48e68a7f15d076227 to your computer and use it in GitHub Desktop.
This example shows the implementation of a method which uses a Promise to report the success or failure of an XMLHttpRequest.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ajax(options) { | |
"use strict"; | |
let promise = new Promise((resolve, reject) => { | |
let xhr = new XMLHttpRequest(); | |
let method = options.method || "GET"; | |
let url = options.url || null; | |
let data = options.data || null; | |
let responseType = options.responseType || "text"; | |
function serialize(obj) { | |
let argCount = 0; | |
let str = ""; | |
for (let key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
if (argCount++) { | |
str += "&"; | |
} | |
str += `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`; | |
} | |
} | |
return str; | |
} | |
xhr.open(method, url); | |
if (method === "POST" || method === "PUT") { | |
if (data && typeof data === "object") { | |
data = serialize(data); | |
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
} | |
} | |
xhr.onload = function() { | |
if (this.status >= 200 && this.status < 300) { | |
resolve(this.response) | |
} else { | |
reject(this.statusText) | |
} | |
}; | |
xhr.responseType = responseType; | |
xhr.send(data); | |
}); | |
return promise; | |
} | |
var data = ajax({ | |
method: "POST", | |
responseType: "json", | |
url: "http://localhost:3000/api/comments", | |
data: { | |
"author": "Fábio Dan", | |
"text": "Lorem ipsum" | |
} | |
}).then((response) => { | |
console.log(response); | |
}).catch((error) => { | |
console.error(error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment