This is a refinement to an earlier JSONp handler where I ran into an issue with accessing the response data due to timing. By passing the resolve and reject behaviours to the "then" method the new promise the data object returned in the callback is accessible. http://www.html5rocks.com/en/tutorials/es6/promises/
Created
May 8, 2017 13:06
-
-
Save linjiang82/19de02083e5a45a45c42790771b61856 to your computer and use it in GitHub Desktop.
Asynch JSONP handler, w/ ECMA6 Promise
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
'use strict'; | |
function Omer(uri, qs) { | |
//Private QueryString Handler | |
function queryString(data) { | |
return Object.keys(data).map(function (key) { | |
return [key, data[key]].map(encodeURIComponent).join('='); | |
}).join('&'); | |
} | |
return new Promise(function(resolve, reject) { | |
var tmstp = Date.now(), | |
fn = 'ajpRsp_' + tmstp, | |
scpe = document.createElement('script'), | |
query = qs && typeof qs === 'object' ? '&' + queryString(qs) : '', | |
elIDpre = uri.split('//')[1].split('/')[0].split('.')[1], | |
url = uri.replace(/callback=\w+/i, 'callback=' + fn); | |
url = query ? url + query : url; | |
//Private Generic "Callback" method resolves/rejects Promise | |
function ajpRsp (tm) { | |
return function (data) { | |
var ajpCk = false, | |
dtype = typeof data, | |
tid = '#'+tm, | |
rmscr = document.querySelector(tid); | |
switch (dtype) { | |
case 'string': | |
ajpCk = JSON.parse(data); | |
break; | |
case 'object': | |
ajpCk = data; | |
break; | |
} | |
document.querySelector('head').removeChild(rmscr); | |
delete window[fn]; | |
if (ajpCk) { | |
resolve(ajpCk); | |
} else { | |
reject(Error('invalid request or empty jsonp object',ajpCk)); | |
} | |
}; | |
} | |
window[fn] = ajpRsp(elIDpre+'_'+tmstp); | |
scpe.type = 'text/javascript'; | |
scpe.src = url; | |
scpe.id = elIDpre+'_'+tmstp; | |
document.querySelector('head').appendChild(scpe); | |
}); | |
} | |
var test = new Omer('https://public-api.wordpress.com/rest/v1/sites/idcdistro.wordpress.com/posts/?callback=ajpRsp',{}); | |
test.then(postCount).catch(function(error) { | |
console.error('Failed!', error); | |
}); | |
function postCount(data) { | |
var p = document.createElement('P'), | |
offset = Object.keys(data.posts).length, | |
ptxt = document.createTextNode('Successfully found '+offset+' of '+data.found); | |
document.body.appendChild(p.appendChild(ptxt)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment