繁体   English   中英

我如何理解 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 行代码的用法会很棒。

那是什么

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

每一行到底是做什么的:

//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. 避免对并发问题使用队列策略。 如果需要使用“队列”策略,请采取措施限制队列长度
  3. 添加一些指示,以便用户看到该按钮起作用并且请求正在发生。 使用 ember-concurrency 很容易做到

暂无
暂无

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

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