Created
March 8, 2019 06:46
-
-
Save dekadentno/db9a8174c10636f25cf5f6a0cdb2f8c8 to your computer and use it in GitHub Desktop.
My backup of a javascript async queue implementation by Bolerodan on CodeSandbox. All regards to him.
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
// the retry service | |
// retry-queue.js | |
const service = { | |
retryQueue: [], | |
onItemAddedCallbacks: [], | |
hasMore () { | |
return this.retryQueue.length > 0 | |
}, | |
push (retryItem) { | |
this.retryQueue.push(retryItem) | |
this.onItemAddedCallbacks.forEach((cb) => { | |
cb(retryItem) | |
}) | |
}, | |
pushRetryFn ({reason, retryFn}) { | |
return new Promise((resolve, reject) => { | |
const retryItem = { | |
reason, | |
retry() { | |
console.log('retrying this promise') | |
return Promise.resolve(retryFn()) | |
.then((value) => resolve(value), | |
(value) => reject(value)) | |
}, | |
cancel() { | |
return reject() | |
} | |
} | |
this.push(retryItem) | |
}) | |
}, | |
retryAll () { | |
return new Promise((resolve, reject) => { | |
while (this.hasMore()) { | |
this.retryQueue.shift().retry() | |
} | |
resolve() | |
}) | |
}, | |
clearAll () { | |
this.retryQueue = [] | |
}, | |
cancelAll() { | |
while (this.hasMore()) { | |
this.retryQueue.shift().cancel() | |
} | |
} | |
} | |
export default service | |
// somewhere else, queue some API calls | |
// interceptors.js | |
import ServiceQueue from './retry-queue.js'; | |
const promise = ServiceQueue.pushRetryFn({ | |
reason: "failed-request", | |
config: API_CONFIG, // my modification | |
retryFn: () => { | |
console.log("CB at interceptor", API_CONFIG); | |
return axios(API_CONFIG); | |
} | |
}); | |
return promise; | |
// retry all queued API calls when wanted | |
// component.vue | |
import ServeiceQueue from './retry-queue.js'; | |
ServiceQueue.retryAll(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment