javascriptnode.jspromisegeneratorco

Why is node.js generator not working as expected?


Given the following two code snippets, why is the transaction object visible in the working case but not visible in the other case?

Working case:

return db.transaction(function(transaction) {
  return co(function*() {
    // transaction is visible, do something with it -> works
  }
}

Not working case:

var c = co(function*() {
   // transaction is NOT visible -> does not work!
});

return db.transaction(function(transaction) {
  return c;
});

Is it possible to make transaction visible in the second case?


Solution

  • why is the transaction object visible in the working case but not visible in the other case?

    Closures. When a function object is created, it just captures all the variables in the surrounding scope. In the first case, when the generator function is created, it has a variable called transaction in the surrounding scope. So, when it is actually invoked, the transaction is available in the scope.

    But in the second case, when the generator function is created, transaction is not available.


    To fix this, you need to explicitly pass the transaction object around. Maybe like this

    function c(transaction) {
      return co(function*() {
        // transaction will be available now
      });
    }
    
    return db.transaction(function(transaction) {
      return c(transaction);
    });