Skip to content

Instantly share code, notes, and snippets.

@kimhogeling
Created March 11, 2016 17:58
Show Gist options
  • Save kimhogeling/a8e69b4121db4047842f to your computer and use it in GitHub Desktop.
Save kimhogeling/a8e69b4121db4047842f to your computer and use it in GitHub Desktop.
Fun with promises using the suggestor of shopping24.de
/**
* 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)
@kimhogeling
Copy link
Author

Result:
Result of AJAX passed by promise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment