On 10/8/13 9:14 PM, Dave Townsend wrote:
I was asked to clarify what I meant by my two examples so here are some
snippets of code that illustrate it. This is forcibly async but you get the
point I hope. If you want to add three numbers you can define:

function add3(foo, bar, baz) {
   return Task.spawn(() => {
     let sum = yield add2(foo, bar);
     return yield add2(sum, baz);
   });
}

Then you need add2 which you can define as either:

function add2(a, b) {
   let sum = yield a + b;
   return sum;
}

or as:

function add2(a, b) {
   return Task.spawn(() => {
     let sum = yield a + b;
     return sum;
   });
}

The latter is certainly a little more verbose with two additional lines of
code and some extra indentation but it is also usable standalone whereas
the first example isn't, you need to know how to call it as a generator.

For this example, the 2nd implementation is clearly better. But a generic answer is "it depends."

If the function/API is effectively a "transaction" then we should return a single promise [from a Task.spawn()]. If it's not a transaction - i.e. it's used as an emitter/stream - then generator functions may be acceptable.

Also, this JS is invalid because a generator function cannot return a value through "return." For people learning at home, a working implementation is:

function add2(a, b) {
  return Task.spawn(function () {
    let sum = yield a + b;
    throw new Task.Result(sum);
  });
}
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to