我想通过重复调用带有键的函数来优化多个昂贵的服务器调用,并返回对象的承诺。解析后,保证对象包含所需的键+某个值,并且它可以包含其他不相关的键。该功能将:
是否有任何NPM库可以帮助解决这个问题,或者我应该从头开始编写它?
答案 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);