diff --git a/index.js b/index.js index 66a8427f..93842b72 100644 --- a/index.js +++ b/index.js @@ -52,6 +52,7 @@ class Analytics { this.flushInterval = options.flushInterval || 10000 this.flushed = false this.errorHandler = options.errorHandler + this.pendingFlush = null Object.defineProperty(this, 'enable', { configurable: false, writable: false, @@ -236,7 +237,7 @@ class Analytics { * @return {Analytics} */ - flush (callback) { + async flush (callback) { callback = callback || noop if (!this.enable) { @@ -254,6 +255,13 @@ class Analytics { return Promise.resolve() } + try { + if (this.pendingFlush) { await this.pendingFlush } + } catch (err) { + this.pendingFlush = null + throw err + } + const items = this.queue.splice(0, this.flushAt) const callbacks = items.map(item => item.callback) const messages = items.map(item => item.message) @@ -291,7 +299,8 @@ class Analytics { req.timeout = typeof this.timeout === 'string' ? ms(this.timeout) : this.timeout } - return this.axiosInstance.post(`${this.host}${this.path}`, data, req) + return (this.pendingFlush = this.axiosInstance + .post(`${this.host}${this.path}`, data, req) .then(() => { done() return Promise.resolve(data) @@ -310,7 +319,7 @@ class Analytics { done(err) throw err - }) + })) } _isErrorRetryable (error) {