[英]How do I understand this custom use of Promise in code
I use some Promise code used in my application as below;我在我的应用程序中使用了一些 Promise 代码,如下所示;
import { Promise, resolve, all } from 'rsvp';
someAction: function(secId, fld, callback) {
var self = this;
var section = self.findSection(self.get('allSecs'), secId);
var myPendingPromise = section.myPendingPromise || resolve();
myPendingPromise = myPendingPromise.then(function(){
return self.myCustomPromise(secId, fld, callback);
});
set(section, 'myPendingPromise', myPendingPromise);
},
myCustomPromise: function(secId, fld, callback){
var self = this;
return new Promise(function(resolve, reject){
var deferred = self.myCustomRule(someFlds); //Makes an API call
deferred.then(function(response) {
resolve(response);
}, function(){
resolve(true);
});
});
},
Now, I am a bit confused why the following lines are added specifically;现在,我有点困惑为什么要特别添加以下几行;
var myPendingPromise = section.myPendingPromise || resolve();
myPendingPromise = myPendingPromise.then(function(){
return self.myCustomPromise(secId, fld, callback);
});
set(section, 'myPendingPromise', myPendingPromise);
Also, I did not find "myPendingPromise" used anywhere else apart from this function.此外,我没有发现除此功能外在其他任何地方使用了“myPendingPromise”。 Is there some pattern which I need to be aware of to be able to understand this code?
是否有一些我需要注意的模式才能理解此代码? It would be great to understand just the usage of these 3 lines of code above.
理解上面这 3 行代码的用法会很棒。
It looks like an attempt to solve concurrency problem by adding all new promises to promise chain (queue).看起来像是通过向承诺链(队列)添加所有新承诺来解决并发问题的尝试。 I prepared a simplified example based on your code that demonstrates how it works.
我根据您的代码准备了一个简化的示例来演示它是如何工作的。
//Extract pending promise from section object. If undefined, use resolve()
//to create and resolve dummy promise:
var myPendingPromise = section.myPendingPromise || resolve();
//Add new promise to chain, so it would start after
//pending promise is resolved:
myPendingPromise = myPendingPromise.then(function(){
return self.myCustomPromise(secId, fld, callback);
});
//Save new promise chain into section object:
set(section, 'myPendingPromise', myPendingPromise);
someAction
is called many times, queue can grow uncontrollably longsomeAction
被多次调用,队列可能会无法控制地增长
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.