Search code examples
javascriptnode.jscallbackcouchdbcouchdb-nano

JavaScript Callback with nano and now.js


everyone.now.getGuess = function(val) {
  db.view('lists', 'project_names', {
      startkey: val,
      endkey: val + "\u9999"
    }, function(_, data) {
    return data.rows.map(function(obj) {
      return obj['key'];
    });
  });

  return this.now.receiveGuess(guesses[0]);
};

db is an object of nano. db.view doesn't return anything and only offers a callback, so guesses = db.view() doesn't work. And within the callback of db.view(), I can't access this for now.js.

How can I solve this?


Solution

  • You can use the var self = this; pattern:

    function a() {
        var self = this;
        foo(function(err, data) {
            /* use "self" instead of "this" here */
        });
    }