繁体   English   中英

JavaScript Promise.then回滚

[英]JavaScript Promise.then rollback

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

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

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

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

同样,在某些情况下,store.load方法可能在整个应用程序生命周期中根本无法执行,因为实际应用程序中的store.load方法是在某些用户活动之后启动的。 存储对象具有单个实例,并且在应用程序生命周期中永久存在。 几次之后,promise可以保留大量物品并防止模型被删除。

您能否建议我一种解决此问题的方法,还是建议另一种通用方法。

当然,我可以兑现承诺。

通常,我的逻辑是这样的:创建许多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(); 

我不确定是否有可能实现真正的承诺,这就是为什么我只是编写自己的实现:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM