Created
March 11, 2016 17:58
-
-
Save kimhogeling/a8e69b4121db4047842f to your computer and use it in GitHub Desktop.
Fun with promises using the suggestor of shopping24.de
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
/** | |
* Let's have some fun with promises using the suggestor of shopping24.de | |
* The coolness is at the bottom of this file! | |
* Caution: This code only works in the console of shopping24.de because we don't allow cross domain calls | |
*/ | |
/** | |
* This is where the magic happens | |
* The AJAX is wrapped by a shiny Promise | |
*/ | |
function getSuggestionsForQuery(query) { | |
/** | |
* Create and return the promise | |
* At AJAX `onload` either resolve or reject depending on the status code | |
* At AJAX `onerror` reject | |
*/ | |
return new Promise(function (resolve, reject) { | |
var request = new XMLHttpRequest() | |
request.onload = function () { (request.status >= 200 && request.status < 400) && resolve(JSON.parse(request.response)) || reject(new Error(request.status)) } | |
request.onerror = function () { reject(new Error('Oh noooz, AJAX failed!')) } | |
request.open('GET', '/suggestor?q=' + query, true) | |
request.send() | |
}) | |
} | |
// Make console.table look nicer (arrow functions would make this line look awesome!) | |
function transform2DArrayTo3D(arr) { return arr.map(function (cell) { return { 'Value': cell } }) } | |
function printAsTable(data) { console.table(data) } | |
function printError(error) { console.error(error) } | |
// Finally use the functions | |
// Yeah, we still have callbacks here, BUTT this is super pretty! | |
// No comments needed, such self explanatory! | |
getSuggestionsForQuery('orange') | |
.then(transform2DArrayTo3D) | |
.then(printAsTable) | |
.catch(printError) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result:
