ES 7 async/await demo!
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! |
This comment has been minimized.
This comment has been minimized.
@meteormatt what version of Babel you have installed? |
This comment has been minimized.
This comment has been minimized.
I am getting |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
I run
build.sh
, but get this error