Created
November 11, 2017 14:11
-
-
Save ElMatella/0079cfa58bb190d80e9c41912a3bca20 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export default class HttpQueue { | |
constructor (queryFunction) { | |
this.requesting = false | |
this.stack = [] | |
this.queryFunction = queryFunction | |
} | |
add (options, resolve, reject) { | |
if (this.stack.length < 2) { | |
return new Promise ((resolve, reject) => { | |
this.stack.push({ | |
options, | |
resolve, | |
reject | |
}) | |
this.makeQuery() | |
}) | |
} | |
return new Promise ((resolve, reject) => { | |
this.stack[1] = { | |
options, | |
resolve, | |
reject | |
} | |
this.makeQuery() | |
}) | |
} | |
makeQuery () { | |
if (! this.stack.length || this.requesting) { | |
return null | |
} | |
this.requesting = true | |
this.queryFunction(this.stack[0].options).then(response => { | |
this.stack[0].resolve(response) | |
this.requesting = false | |
this.stack.splice(0, 1) | |
this.makeQuery() | |
}).catch(error => { | |
this.stack[0].reject(error) | |
this.requesting = false | |
this.stack.splice(0, 1) | |
this.makeQuery() | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment