javascript - 链式 promise 和原型(prototype) `this`

标签 javascript angularjs jasmine karma-jasmine angular-promise

我很难获得在原型(prototype)中使用正确的 this 范围的 promise 。

这是我的代码:

'use strict';

angular.module('testApp').factory('UrlSearchApi',
  function($resource, URL_SEARCH_API, PAGE_SIZE, $q){

  var resource = $resource(URL_SEARCH_API);

  resource.Scroll = function () {
    return this.reset();
  };

  resource.Scroll.prototype.reset = function () {
    this.visibleItems = [];
    this.allItems = [];
    this.busy = null;
    return this;
  };

  resource.Scroll.prototype.fetch = function(query){
    var params = {};
    if(query) { params.q = query; }
    return resource.query(params).$promise;
  };

  resource.Scroll.prototype.loadAllItems = function (results) {
    var d = $q.defer();

    angular.forEach(results, function (result, i) {
      this.allItems.push(result);
      if(i === results.length - 1 ) { d.resolve(); }
    }, this);

    return d.promise;
  };

  resource.Scroll.prototype.loadVisibleItems = function () {
    var length = this.visibleItems.length,
        offset = parseInt(length / PAGE_SIZE),
        start = PAGE_SIZE * offset,
        end = start + PAGE_SIZE,
        subset = this.allItems.slice(start, end),
        d = $q.defer();

    angular.forEach(subset, function (item, i) {
      this.visibleItems.push(item);
      if(i === subset.length - 1 ) { d.resolve(); }
    }, this);

    return d.promise;
  };

  resource.Scroll.prototype.nextPage = function (query) {
    if(this.busy) { return; }

    console.log('nextPage ', query);
    var tasks = [],
        that = this;

    if(!this.allItems.length) {
      this.reset();
      this.busy = true;
      return this.fetch(query)
        .then(this.loadAllItems)
        .then(this.loadVisibleItems)
        .finally(function () {
          this.busy = false;
        });
    } else {
      this.busy = true;
      return this.loadVisibleItems().finally(function () {
        this.busy = false;
      });
    }
  };

  return resource;
});

每当我运行测试时,我都会得到

describe('#nextPage', function () {
  var scroll;

  describe('when there is NO search term (show all)', function () {

    beforeEach(function (done) {
      scroll = new UrlSearchApi.Scroll();

      $httpBackend.expectGET('/policy/search')
        .respond(200, arrayGenerator(123));
      scroll.nextPage().then(done);
      $httpBackend.flush();
      $rootScope.$apply();
    });

    it('should load all the items in all items variable', function () {
      expect(scroll.allItems.length).toBe(123);
    });
 });

});

我收到以下错误:

TypeError: 'undefined' is not an object (evaluating 'this.allItems')

我现在在严格模式下的 $qthen 中的 this 设置为 undefined。我尝试在多个地方使用 bind(this) 但不是运气......有什么想法吗?

最佳答案

我已经回答过这样的问题here . 如果您仍有疑问,请在评论中告诉我。

更新。尝试像这样更新您的 resource.Scroll.prototype.nextPage 方法:

if(!this.allItems.length) {
      this.reset();
      this.busy = true;
      return this.fetch(query)
        .then(this.loadAllItems.bind(this)) //bind here
        .then(this.loadVisibleItems.bind(this)) // here
        .finally(function () {
          this.busy = false;
        }.bind(this)); //and here

但请记住 - 当您将函数作为回调传递thenforEach 等时 失去这个上下文。因此,当您传递使用 this 语法作为回调的函数时,请准确使用 bind

关于javascript - 链式 promise 和原型(prototype) `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34455585/

相关文章:

javascript - Jasmine 规范运行者 : Stack Trace from failed test?

javascript - 如何更改浏览器选项卡在 JSFiddle 中显示的文本

javascript - 如何在AJAX中获取选择表单的值?

javascript - 正则表达式检测 JavaScript

javascript - 如何通过 Parse REST API 从 _User 中删除用户

javascript - 从 Controller 访问模型。 Angular .js

javascript - 测试使用 setInterval 或 setTimeout 的 Angular2 组件

javascript - dom-repeat with `<span>` 空白解决方案

javascript - 使用另一个数据源作为默认选择时,从 ui-select 选项中删除重复项

javascript - 如何使用spyOn模拟Jasmine中选择器的jQuery值?