Skip to content

Instantly share code, notes, and snippets.

@MrBenJ
Last active October 2, 2018 00:41
Show Gist options
  • Save MrBenJ/23bfdda11f2bd549c170a44f1990807e to your computer and use it in GitHub Desktop.
Save MrBenJ/23bfdda11f2bd549c170a44f1990807e to your computer and use it in GitHub Desktop.
A real world example of how JS Promises work (A+ Specification)
import { getJSON } from './promise_example';
function init() {
getJSON('my-url.com').then( data => {
// data, the first param of resolve(), contains
// the response data from the XHR request
console.log(data);
}).catch( error => {
// oh no, something went wrong!
// error is the first param of reject()
console.error(error
});
}
init();
export function getJSON(url) {
return new Promise( (resolve, reject) => {
// Parse the URL:
if(url.includes('?')) {
if(url[url.length - 1] !== '&') {
url += '&';
}
url += '_=' + Date.now();
}
else {
url += '?_=' + Date.now();
}
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader('Accept', 'application/json, text/tavascript, */*; q=0.01');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.setRequestHeader('Cache-Control', 'no-cache, no-store');
xhr.onreadystatechange = () => {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
reject(xhr.response);
}
if(xhr.readyState === 4) {
resolve(JSON.parse(xhr.response));
}
}
xhr.send();
});
}
import { getJSON } from './promise_example';
async function mutipleCallExample() {
// Always wrap your async/await calls in try/catch.
// it's best practice :)
try {
const firstCallResponse = await getJSON('one-url.com');
const secondCallResponse = await getJSON('two-url.com');
// this will return the resolved promises in its own promise
return { first: firstCallResponse, second: secondCallResponse };
} catch( error) {
// If something goes wrong with any of the calls above, then
// throw an error
throw new Error(error);
}
}
function init() {
// Async functions return a promise, so you'll need to use .then()
// to get the response inside.
multipleCallExample().then( result => {
console.log(result);
// This console.log shows:
// { first: firstCallResponse, second: secondCallResponse }
}).catch( error => {
// Something went wrong in our big call!
console.error(error);
});
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment