sails.js Controllers Using ES2015 generators with co.js


Example

'use strict';

const co = require('co');

module.exports = {
  // This is the index action and the route is mapped via /config/routes.js
  index(req, res) {
    co(function* index() {
      // Return a view without view model data
      // This typically will return the view defined at /views/home/index.<view engine extension>
      return res.view();
    }).catch(res.negotiate); // Catch any thrown errors and pass the error to the `negotiate` policy.
  },
  foo(req, res) {
    co(function* foo() {
      // Get an array of `FooBar` items from the database
      const items = yield FooBar.find();

      // Return the 'foo' view with a view model containing the array of `FooBar` items
      return res.view({
        items,
      });
    }).catch(res.negotiate); // Catch any thrown errors and pass the error to the `negotiate` policy.
  },
};