I'm pretty happy with tamejs, it makes my javascript code much clearer. But I still feel the error handling is a little boring.
See the code:
// callback should be callback(err, nextInt)
function inc(n, callback) {
setTimeout(function() {
callback(null, n+1);
}, 100);
}
await { inc(3, defer(var err, next));}
if(err) throw new Error(err); // !!! error handling
await { inc(8, defer(var err, next));}
if(err) throw new Error(err); // !!! error handling
await { inc(12, defer(var err, next));}
if(err) throw new Error(err); // !!! error handling
await { inc(39, defer(var err, next));}
if(err) throw new Error(err); // !!! error handling
Since nearly every asynchronous api has callbacks which have a error
as the first parameter, we need to get it and check it first.
You can see there are a lot of error handling lines in the sample, which is boring.
Is there any way to simplify it?
function asyncCheck(workFunction) {
await { workFunction(defer(var err, next)) };
if (err) throw new Error(err);
}
//Then use closures to define the work
asyncCheck(function (callback) { inc(2, callback}));
I haven't tried tamejs myself, just read about it, but perhaps this pattern will work?