簡體   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