我如何理解 Promise 在代码中的这种自定义用法

How do I understand this custom use of Promise in code

我在我的应用程序中使用了一些 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);
        });
    });
},

现在,我有点困惑为什么要专门添加以下几行;

var myPendingPromise = section.myPendingPromise || resolve();
myPendingPromise = myPendingPromise.then(function(){
    return self.myCustomPromise(secId, fld, callback);
});
set(section, 'myPendingPromise', myPendingPromise); 

此外,我没有发现 "myPendingPromise" 除了这个功能外还用在其他任何地方。为了能够理解这段代码,我需要注意一些模式吗? 如果能理解上面这3行代码的用法就太好了。

那是什么

它看起来像是通过将所有新的承诺添加到承诺链(队列)来解决并发问题的尝试。我根据您的代码准备了一个简化的 example 来演示它是如何工作的。

每一行的具体作用:

//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); 

为什么它是并发问题的糟糕解决方案(我的意见)

  1. 有点难以阅读和理解
  2. 如果 promise 需要很长时间才能完成并且 someAction 被多次调用,队列可能会不受控制地变长
  3. 似乎没有任何东西向用户表明某些东西是 运行

什么是好的解决方案(再次,我的意见)

  1. 使用像 ember-concurrency 这样的库来管理并发性
  2. 避免使用队列策略解决并发问题。如需使用"queue"策略,请采取限制队列长度
  3. 的措施
  4. 添加一些指示,以便用户看到该按钮有效并且请求正在发生。使用 ember-concurrency
  5. 很容易做到