Skip to content

Instantly share code, notes, and snippets.

@etoxin
Last active May 16, 2018 11:22
Show Gist options
  • Save etoxin/28a4e46081506944dc46d84571d3c3aa to your computer and use it in GitHub Desktop.
Save etoxin/28a4e46081506944dc46d84571d3c3aa to your computer and use it in GitHub Desktop.
Promise Example
/**
* @example
*
* import {getLocation} from './services/getLocation';
* getLocation().then(res => {
* console.log(res);
* });
*
* @returns {Promise<any>}
*/
export function getLocation() {
return new Promise(function(resolve, reject) {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function (position) {
resolve(position.coords.latitude, position.coords.longitude);
});
} else {
reject(false);
}
});
}
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
var request = new XMLHttpRequest();
request.open('GET', 'https://www.reddit.com/r/webdev/top.json', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
resolve(JSON.parse(this.response));
} else {
// We reached our target server, but it returned an error
reject("Error");
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
});
promise.then(function(webDevTop) {
console.log(webDevTop);
}, function(err) {
console.log(err); // Error: "It broke"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment