JavaScript Promise.then回滚

时间:2016-09-28 13:05:05

标签: javascript promise

我的应用程序中有一个模型和类似商店的东西。模型对象是使用promise等待来自商店的数据。

但是对于某些情况我需要删除模型,但因为我使用了promise我的模型仍处于关闭状态,GC无法清理对象。

我正在寻找一种如何从Promise对象中删除处理程序的方法。

在下面的示例中,我创建了两个模型对象,并尝试从内存中删除其中一个。

此外,在某些情况下,在所有应用程序生命周期内都无法执行store.load方法,因为实际应用程序中的store.load方法在某些用户活动之后启动。 store对象具有单个实例,并且在应用程序生命周期中永久存在。经过几次,承诺可以保留一堆物品,防止模型被删除。

您能否建议我如何解决此问题,或建议另一种通用方法。

当然,我可以远离承诺。

一般来说,我的逻辑就像:创建很多UI元素包装器(其中一些会死掉一些,其中一些会永远存在),等待一些用户活动,当用户抓住应用程序加载一些数据然后模型也应该使用这些数据。



  var createModel = function(dataStore, name) { 
     var obj = {
         linkToDOM: { name: name, text: 'Here should be a link to the DOM object and etc.' },
         init: function(data) { data.whenLoaded().then(this.run.bind(this)); },
         run: function(data) { console.log('Do hard work with DOM and data', this.linkToDOM, data); },
         remove: function() { delete this.linkToDOM; delete this.run; console.log('Can I go away? Pleaseee... Why not!?'); }
     };

     obj.init(dataStore);

     return obj;
  };

  var store = {
     _resolve: undefined,
     _loadPromise: undefined,

     init: function() {
        var self = this;
        this._loadPromise = new Promise(function(resolve) { self._resolve = resolve; });
     },

     whenLoaded: function() {
        return this._loadPromise;
     },

     load: function() {
        var self = this;
        setTimeout(() => { 
          self._resolve({msg: 'loaded', data: {a:1}}); 
        }, 1000);

     }
  }

  store.init();

  var model1 = createModel(store, 'model 1');
  var model2 = createModel(store, 'model 2');

  store.load();

  // I don't need you any more!
  model1.remove();




1 个答案:

答案 0 :(得分:2)

如果它有可能带有真正的承诺,我不是真的,这就是为什么我只是编写一个自己的实现:

function prom(){
console.log("prom registered");
this.funcs=[];
}
prom.prototype.then=function(func){
this.funcs.push(func);
console.log("callback added");
return this.funcs.length-1;
}
prom.prototype.resolve=function(){
this.funcs.forEach((func)=>{func();});
console.log("resolved");
}
prom.prototype.dismiss=function(id){
this.funcs.splice(id,1);
console.log("callback destroyed");
}

像这样使用:

store=new Prom();
id=store.then(function(){});
store.dismiss(id);
store.resolve();//silence