将数据从promise然后方法传递给对象方法

时间:2016-05-06 07:38:50

标签: javascript node.js promise javascript-objects

如何将data从promise then方法传递给对象方法。

this.httpReq(url).then(function (data) {
  this.storeData(data);
});

我知道我在这里超出了范围而this没有引用我的对象。但是,尽管如此,我无法理解如何解决它。 Bellow你可以找到整个代码片段。
最后,我想从服务API获取数据并将其存储在对象数组属性this.storage中。

var http = require('http');

function CoubApi (url) {
  this.url = url;
  this.storage = [];
  this.httpReq = httpReq;
  this.searchData = searchData;
  this.storeData = storeData;
}

function httpReq (url) {
  var promise = new Promise (function (resolve, reject) {

    http.get(url, function (res) {
      var data = '';

      res.on('data', function (chunk) {
        data += chunk;
      });

      res.on('end', function () {
        if(data.length > 0) {
          resolve(JSON.parse(data));
        } else {
          reject("Error: HTTP request rejected!");
        }
      });

    }).on('error', function (err) {
      console.log("Error: ", e);
    });

  });

  return promise;
}

function storeData (data) {
  var i;
  console.log("Storrrreee");
  for(i = 0; i < 10; i++) {
    this.storage.push(data.coubs[i]);
  }
}

function searchData (searchtext, order, page) {
  var url = this.url+
            "search?q="+searchtext+
            "&order_by="+order+
            "&page="+page;


  this.httpReq(url).then(function (data) {
    this.storeData(data);
  });
}

var coub = new CoubApi("http://coub.com/api/v2/");
coub.searchData("cat", "newest_popular", 1);
console.log(coub.storage);

1 个答案:

答案 0 :(得分:3)

您可以将其存储在变量中:

var self = this;
this.httpReq(url).then(function (data) {
  self.storeData(data);
});

或使用bind:

this.httpReq(url).then(function (data) {
  this.storeData(data);
}.bind(this));
相关问题