1

Using superagent package in nodejs, I'm not sure about what I can do in .end().

I'm trying to alter the values of 'title' and 'description' after getting data in 'get' function, but they remains the same.

Also when I tried to return the data.body[0].title in .end(), then

var todo = new Todo();
console.log(todo.get());

it said it's undefined. How do I change the value of Todo's properties with superagent syntax?

Code as below:

function Todo() {
  this.title = "milk";
  this.description = "ok, Milk is a white liquid produced by the mammary glands of mammals.";
}

util.inherits(Todo, Model);

Todo.prototype.get = function() {
  console.log(this.title);
  request
    .get(this.read().origin + '/todos/11' + '?userId=1&accessToken=' + this.read().accessToken)
    .send({
      username : 'jiayang',
      password : 'password',
      clientId : this.read().clientId,
      clientSecret : this.read().clientSecret
    })
    .end(function(data) {
      console.log(data.body[0]);
      this.title = data.body[0].title;
      this.description = data.body[0].description;
    });
};
Jiayang
  • 738
  • 1
  • 7
  • 13

1 Answers1

1

The context of this in the end callback is the local scope of the callback function.

Try;

Todo.prototype.get = function() {
  var self = this;

  console.log(this.title);
  request
    .get(this.read().origin + '/todos/11' + '?userId=1&accessToken=' + this.read().accessToken)
    .send({
      username : 'jiayang',
      password : 'password',
      clientId : this.read().clientId,
      clientSecret : this.read().clientSecret
    })
    .end(function(data) {
      console.log(data.body[0]);
      self.title = data.body[0].title;
      self.description = data.body[0].description;
    });
};
Bulkan
  • 2,555
  • 1
  • 20
  • 31
  • It was because that executing the request takes time. So it logs the original 'title' even when I do console.log after calling 'get' function. Thank you! – Jiayang May 29 '14 at 08:14
  • Can I return things in .end? like return data.body – Jiayang May 29 '14 at 10:19
  • @Jiayang no as there would be nobody listening and waiting for the returned value. It is about the asynchronous nature of processing events through callbacks etc. There are some workarounds (e.g. http://stackoverflow.com/a/18229477/2626313) but before choosing one you should make sure you understand the basics, check http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js – xmojmr May 31 '14 at 13:27