Writing sync code with Javascript

We all heard about “callback hell” which is arguably the ugliest thing in javascript and the so called solution to it “promise chains”

// callback hell
someFunc(function(err, result) {
if (err) return doSomethingWithError();
someOtherFunc(result, function(err, anotherResult) {
if (err) return doSomethingWithError();
// go on…
});
});
// promise chains
someFunc().then(
function (result) {
return someOtherFunc(result);
}
).then(
function (anotherResult) {
}
).catch(
function (error) {
domeSomethingWithError(error);
}
);

You see? promise chains are a little bit better than callbacks, but still very ugly. Let me show how it will change how you write javascript code. First fetch it from NPM by typing

npm install --save asynquence asynquence-contrib

Then import the library

const ASQ = require("asynquence-contrib");

Finally the usage

ASQ().runner(function *() {
const result = yield someFunc();
const anotherResult = yield someOtherFunc(result);
}).or(
function (error) {
doSomethingWithError(error);
}
);

Much better and readable in my opinion.. If I’ve been stuck with callback hell, I most likely would give up with javascript. Kudos to these guys for this beautiful library.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.