0

I know out of the box Q won't support this, but I'm wondering if it is theoretically possible to do something like this:

var user = Q.spawn(function* () {
    var createdUser = yield createUser();
    return user;
});

console.log(user); // user is available here
Kirk Ouimet
  • 27,280
  • 43
  • 127
  • 177

1 Answers1

0

I may be wrong, but I would say yes, it is possible theoretically, it's just not intended to work like that. That's why Q doesn't support it.

I'm not sure why Q.done doesn't invalidate the promise chain altogether, preventing further calls to p.then to succeed (maybe it's impossible), but right now (Q is at version 1.2.0 at the time of this writing) it doesn't:

var p = Q("Test");
p.done();
p.then(function(message) {
    console.log(message); // "Test" is logged here just fine.
});
// No runtime errors.

So Q.spawn needed only return the result of Q.async(generator)() after calling Q.done on it to support that, like this:

Q.spawn = spawn;
function spawn(makeGenerator) {
    var p = Q.async(makeGenerator)();
    Q.done(p);
    return p;
}

That said, it seems clear to me that the API doesn't want to encourage using a done promise chain: Contrary to Q.then and Q.catch, for example, neither Q.done nor Q.spawn return any promise for chaining.

The library authors were either not sure if this was a good idea (and so didn't want to encourage it, but didn't also implement something that prohibits done promises from being used) or were outright convinced it's not.

Gui Prá
  • 5,559
  • 4
  • 34
  • 59