Move request-queue into standalone package
parent
b2224d3e0f
commit
4842920469
@ -1,63 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
const Promise = require("bluebird");
|
||||
const pDefer = require("p-defer");
|
||||
|
||||
module.exports = function createRequestQueue(options = {}) {
|
||||
let requestBuffer = [];
|
||||
let responseBuffer = [];
|
||||
let seenError;
|
||||
|
||||
function failAllRequests(error) {
|
||||
let failedRequests = requestBuffer;
|
||||
requestBuffer = [];
|
||||
|
||||
seenError = error;
|
||||
|
||||
for (let request of failedRequests) {
|
||||
request.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
function maybeOnMatch() {
|
||||
if (options.onMatch != null) {
|
||||
return Promise.try(() => {
|
||||
return options.onMatch();
|
||||
}).catch((error) => {
|
||||
failAllRequests(error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pushRequest: function () {
|
||||
if (responseBuffer.length > 0) {
|
||||
let returnValue = Promise.resolve(responseBuffer.shift());
|
||||
maybeOnMatch();
|
||||
return returnValue;
|
||||
} else if (seenError !== undefined) {
|
||||
return Promise.reject(seenError);
|
||||
} else {
|
||||
let { resolve, reject, promise } = pDefer();
|
||||
requestBuffer.push({ resolve, reject });
|
||||
return promise;
|
||||
}
|
||||
},
|
||||
pushResponse: function (response) {
|
||||
if (requestBuffer.length > 0) {
|
||||
let request = requestBuffer.shift();
|
||||
request.resolve(response);
|
||||
maybeOnMatch();
|
||||
} else {
|
||||
responseBuffer.push(response);
|
||||
}
|
||||
},
|
||||
failAllRequests: failAllRequests,
|
||||
requestCount: function () {
|
||||
return requestBuffer.length;
|
||||
},
|
||||
responseCount: function () {
|
||||
return responseBuffer.length;
|
||||
}
|
||||
};
|
||||
};
|
Loading…
Reference in New Issue