javascriptnode.jskoaco

Loosing parameters passed from co-wrapped function to another one


I'm using the latest co-module (4.6).

This is a Koa-middleware. Therefore it is already co() wrapped.

create: function * () {
  try {
    this.body = yield services.createIt({obj: true})
  } catch (err) {
    this.body = { "errors": err.details }
    this.status = err.status
  }
}

It is calling another generator-function I'm manually wrapping with co:

const co = require('co')

createIt: co(function * (obj) {
  console.log(obj) // --> undefined
}

Why do I "loose" the parameter?


Solution

  • The function co immediately executes the given generator function with the async/await semantics. If you are just using it from a Koa-middleware, you don't need to wrap the createIt function with co, or you can just use co.wrap to turn the generator into a function that returns a promise (delayed promise). Check https://github.com/tj/co/blob/master/index.js#L26

    create: function * () {
      try {
        this.body = yield services.createIt({obj: true})
      } catch (err) {
        this.body = { "errors": err.details }
        this.status = err.status
      }
    }
    

    services.js

    const co = require('co')
    
    createIt: function * (obj) {
      console.log(obj)
    }
    
    // OR
    
    createIt: co.wrap(function *(obj) {
      console.log(obj);
    });