Previsouly I had written a post on intro to ES7/ES2016 async-await in this post I shall take a simple example which shall demonstarte ways to reach to a callbackless code.
Getting a random comic with xkcd-imgs module.
var xkcd = require('xkcd-imgs');
xkcd.img(function(err, res){
if(!err) {
console.log(res);
}
});
Same code with async-await
var promisify = require('es6-promisify');
var xkcd = promisify(require('xkcd-imgs').img);
console.log(await xkcd());
Let us consider more generic example of fetching some data from an URL. (Internals of xkcd-imgs
module)
var request = require('request');
request('http://xkcd-imgs.herokuapp.com/', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
var result = JSON.parse(await require("request-promise")('http://xkcd-imgs.herokuapp.com/'));
console.log(result);
Or you could use the fetch
API
var fetch = require('node-fetch');
await (await fetch('http://xkcd-imgs.herokuapp.com/')).json();
Indeed there babeljs to take care of async-await
compilation for you!
So dive in and enjoy async programming in JavaScript without callbacks ;)