1

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?

4

1 回答 1

0
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}));

我自己没有尝试过 tamejs,只是阅读了一下,但也许这种模式会起作用?

于 2012-05-19T16:21:50.280 回答