Async logger service using javascript
class LoggerService {
packSizeLimit = 3
isServerReady = true
queue = []
getIsServerReady() {
return this.isServerReady;
}
sendEventsToQueue(data) {
this.queue.push(data);
this.sendEvents();
}
sendEvents() {
if(this.getIsServerReady()) {
const pack = this.queue.splice(0, this.packSizeLimit);
this.sendEventsToServer(pack);
}
}
// max 3 (packSizeLimit) events at a time
// and only after the promise returns success response
sendEventsToServer(list) {
this.isServerReady = false;
const promise = new Promise((res, rej) => {
setTimeout(() => {
res()
}, 2000)
});
promise.then(res => {
this.isServerReady = true;
console.log('success: ', list.length);
if(this.queue.length) {
this.sendEvents();
}
})
}
log(name = '', data) {
const normalizeData = {
name,
data
}
this.sendEventsToQueue(normalizeData);
}
}
console.log('hello Test')
const asyncLog = new LoggerService();
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
asyncLog.log('hello', {sku: 123})
Comments
Post a Comment