结合JS中的多个去抖承诺

时间:2016-10-11 03:29:29

标签: javascript npm es6-promise

我想通过重复调用带有键的函数来优化多个昂贵的服务器调用,并返回对象的承诺。解析后,保证对象包含所需的键+某个值,并且它可以包含其他不相关的键。该功能将:

  • 在第一次通话时,创建一个承诺
  • 每次通话时
  • ,累计要发送到服务器的密钥
  • 所有来电都会返回相同的承诺,直到100ms的安静时间
  • 如果没有拨打100毫秒的电话,请致电服务器处理到目前为止累积的所有密钥
  • 如果进行了新的通话,即使服务器尚未响应,请将其视为"首次通话"通过使用自己的一组待定密钥启动新的承诺
  • 当服务器调用返回时,解决待处理的承诺

是否有任何NPM库可以帮助解决这个问题,或者我应该从头开始编写它?

1 个答案:

答案 0 :(得分:1)

搜索“NPM使用单个承诺整合服务器请求”或“...累积服务器请求...”没有发现任何明显的问题。我将使用评论中提到的ES6承诺共享模型代码,或许在没有其他建议的情况下形成解决方案的基础。按原样,不保证等...

/*******  application code  ********/

function requestKeys( keyArray) {
    // promise an oject for values of keys in keyArray:
    // use asynchronous code to get values for keys in keyArray,
    // return a promise for the parsed result object.
    // ...
}

const latency = 100; // maximum latency between getting a key and making a request

/********  generic code *********/

var getKey = (( requestKeys, latency) => {
    // return a function to return a promise of a key value object
    var promise = null;
    var resolve = null;
    var reject = null;
    var pendingKeys = null;

    var defer = () => {
        promise = new Promise( (r,j) => {resolve = r; reject = j});
        pendingKeys = [];
    };

    var running = false;
    var timesUp = () => {
        resolve( requestKeys( pendingKeys));
        running = false;
    }
    var addKey = ( key) => {
        if(! running) {
            defer();
            setTimeout( timesUp, latency);
            running = true;
        }
        pendingKeys.push( key);
        return promise;
    }
    return addKey;
})( requestKeys, latency);


/*******   test code   *******/

// redefine requestKeys to promise an object with key strings as key values,
// resolve the return promise synchronously for testing:

function requestKeys( keyArray) {
    var keyObj = keyArray.reduce( ((obj, v) => ((obj[v] = v), obj) ), {} );
    return new Promise( (resolve, reject) => resolve(keyObj) );
}

var log = obj => console.log( JSON.stringify(obj));

// get two keys quickly
getKey("holas").then( log);
getKey("buono").then( log);

// wait and get another
setTimeout( function(){getKey('later').then( log)}, 500);