Last active
May 16, 2018 11:22
-
-
Save etoxin/28a4e46081506944dc46d84571d3c3aa to your computer and use it in GitHub Desktop.
Promise Example
This file contains hidden or 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
/** | |
* @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); | |
} | |
}); | |
} |
This file contains hidden or 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
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