Skip to content

Instantly share code, notes, and snippets.

@ricardo-rossi
Forked from patrickarlt/build.sh
Created December 21, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardo-rossi/e55d82fc5463724b48ff to your computer and use it in GitHub Desktop.
Save ricardo-rossi/e55d82fc5463724b48ff to your computer and use it in GitHub Desktop.
ES 7 async/await demo!
babel github-es6.js -o github.js --optional runtime --experimental
import request from "request";
// promise returning function
function get (url){
return new Promise(function(resolve, reject){
request({
method: 'GET',
url: url,
json: true,
headers: {
'User-Agent': 'request'
}
}, function(err, resp, body){
if(err){
reject(err);
} else {
resolve(body);
}
});
});
}
// create a new "async" function so we can use the "await" keyword
async function printPublicGists(){
// "await" resolution or rejection of the promise
// use try/catch for error handling
try {
var gists = await get('https://api.github.com/gists/public');
// now you can write this like syncronous code!
gists.forEach(function(gist){
console.log(gist.description);
});
} catch (e) {
// promise was rejected and we can handle errors with try/catch!
}
}
printPublicGists();
"use strict";
var _core = require("babel-runtime/core-js")["default"];
var _regeneratorRuntime = require("babel-runtime/regenerator")["default"];
var _babelHelpers = require("babel-runtime/helpers")["default"];
var request = _babelHelpers.interopRequire(require("request"));
// promise returning function
function get(url) {
return new _core.Promise(function (resolve, reject) {
request({
method: "GET",
url: url,
json: true,
headers: {
"User-Agent": "request"
}
}, function (err, resp, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
});
});
}
// create a new "async" function so we can use the "await" keywork
function printPublicGists() {
var gists;
return _regeneratorRuntime.async(function printPublicGists$(context$1$0) {
while (1) switch (context$1$0.prev = context$1$0.next) {
case 0:
context$1$0.prev = 0;
context$1$0.next = 3;
return get("https://api.github.com/gists/public");
case 3:
gists = context$1$0.sent;
// now you can write this like syncronous code!
gists.forEach(function (gist) {
console.log(gist.description);
});
context$1$0.next = 9;
break;
case 7:
context$1$0.prev = 7;
context$1$0.t0 = context$1$0["catch"](0);
case 9:
case "end":
return context$1$0.stop();
}
}, null, this, [[0, 7]]);
}
printPublicGists();
// "await" resolution or rejection of the promise
// use try/catch for error handling
// promise was rejected and we can handle errors with try/catch!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment