Created
April 6, 2015 11:18
-
-
Save alyssaq/11791fd1123a6fd03032 to your computer and use it in GitHub Desktop.
ES7 async
This file contains 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
function get(url) { | |
return new Promise(function(resolve, reject) { | |
var req = new XMLHttpRequest(); | |
req.open('GET', url); | |
req.setRequestHeader('User-Agent', 'mralexgray'); | |
req.onload = function() { | |
if (req.status == 200) { | |
resolve(JSON.parse(req.response)); | |
} | |
else { | |
reject(Error(req.statusText)); | |
} | |
}; | |
req.onerror = function() { | |
reject(Error("Network Error")); | |
}; | |
req.send(); | |
}); | |
} | |
var params = '?client_id=5d55f8b2c81b86fc413c&client_secret=f816768d68ca421eef677743218db6e768bc93f6'; | |
//ES7 async/await | |
(async function() { | |
let res = await get('https://api.github.com/users/mralexgray/repos' +params) | |
let res2 = await get('https://api.github.com/users/alyssaq/repos' +params) | |
alert('ES7: ' + res[0].full_name + ',\n' + res2[0].full_name) | |
try { | |
let res2 = await get('https://api.github.com/rubbish' +params) | |
//alert('ES7 GOOD: ' + err) | |
} catch (err) { | |
alert('ES7 BAD: ' + err) | |
} | |
}()); | |
//ES6 Promises | |
get('https://api.github.com/users/mralexgray/repos' +params).then(function (res) { | |
get('https://api.github.com/users/alyssaq/repos' +params).then(function (res2) { | |
//alert('ES6: ' + res[0].full_name + ',\n'+ res2[0].full_name) | |
get('https://api.github.com/rubbish' +params).then(function (res3) { | |
//alert('ES6 GOOD: ' + err) | |
}).catch(function (err){ | |
//alert('ES6 BAD: ' + err) | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment