Last active
March 7, 2020 08:42
-
-
Save jacknie84/2d882fab10617534e9612a17cfbfde1c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(root, factory) { | |
if (typeof define === 'function' && define.amd) { | |
define(factory); | |
} | |
else if (typeof module === 'object' && module.exports) { | |
module.exports = factory(); | |
} | |
else { | |
root.BufferedPayloadQueue = factory(); | |
} | |
}(typeof self !== 'undefined' ? self : this, function() { | |
function BufferedPayloadQueue(bufferSize, poller, timeout) { | |
this.bufferSize = bufferSize || 1; | |
this.poller = poller || 100; | |
this.timeout = timeout || 10000; | |
this.locked = false; | |
this.buffer = []; | |
} | |
function handleResolve(element) { | |
this.add(element); | |
this.locked = false; | |
return Promise.resolve(element); | |
} | |
function handleReject() { | |
this.locked = false; | |
var args = Array.prototype.slice(arguments); | |
var error = new Error('promise error'); | |
error.handleArgs = args; | |
return Promise.reject(error); | |
} | |
var methods = BufferedPayloadQueue.prototype; | |
methods.addPromise = function(promise) { | |
this.locked = true; | |
var resolve = handleResolve.bind(this); | |
var reject = handleReject.bind(this); | |
return promise.then(resolve, reject); | |
}; | |
methods.add = function(element) { | |
if (this.buffer.length >= this.bufferSize) { | |
this.buffer.shift(); | |
} | |
return this.buffer.push(element); | |
}; | |
methods.poll = function() { | |
var that = this; | |
var poller = this.poller; | |
var timeout = this.timeout; | |
return new Promise(function(resolve, reject) { | |
var interval = setInterval(function() { | |
timeout -= poller; | |
if (timeout <= 0) { | |
reject(new Error('timeout error(timeout: ' + timeout + ' ms, poller: ' + poller + ' ms)')); | |
} | |
if (!that.locked) { | |
resolve(this.buffer.shift()); | |
clearInterval(interval); | |
} | |
}, poller); | |
}); | |
}; | |
return BufferedPayloadQueue; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment