I have an array of promises that I would like to call in parallel, but resolve synchronously.
I made this bit of code to do the required task, however, I needed to create my own object QueryablePromise
to wrap the native Promise
that I can synchronously check to see it's resolved status.
Is there any better way to achieve this task that doesn't require a special object?
Please note. I do not want to use
Promise.all
as I don't want to have to wait for all promises to resolve before processing the effects of the promises. And I cannot useasync
functions in my code base.
const PROMISE = Symbol('PROMISE')
const tap = fn => x => (fn(x), x)
class QueryablePromise {
resolved = false
rejected = false
fulfilled = false
constructor(fn) {
this[PROMISE] = new Promise(fn)
.then(tap(() => {
this.fulfilled = true
this.resolved = true
}))
.catch(x => {
this.fulfilled = true
this.rejected = true
throw x
})
}
then(fn) {
this[PROMISE].then(fn)
return this
}
catch(fn) {
this[PROMISE].catch(fn)
return this
}
static resolve(x) {
return new QueryablePromise((res) => res(x))
}
static reject(x) {
return new QueryablePromise((_, rej) => rej(x))
}
}
/**
* parallelPromiseSynchronousResolve
*
* Call array of promises in parallel but resolve them in order
*
* @param {Array<QueryablePromise>} promises
* @praram {Array<fn>|fn} array of resolver function or single resolve function
*/
function parallelPromiseSynchronousResolve(promises, resolver) {
let lastResolvedIndex = 0
const resolvePromises = (promise, i) => {
promise.then(tap(x => {
// loop through all the promises starting at the lastResolvedIndex
for (; lastResolvedIndex < promises.length; lastResolvedIndex++) {
// if promise at the current index isn't resolved break the loop
if (!promises[lastResolvedIndex].resolved) {
break
}
// resolve the promise with the correct resolve function
promises[lastResolvedIndex].then(
Array.isArray(resolver)
? resolver[lastResolvedIndex]
: resolver
)
}
}))
}
promises.forEach(resolvePromises)
}
const timedPromise = (delay, label) =>
new QueryablePromise(res =>
setTimeout(() => {
console.log(label)
res(label)
}, delay)
)
parallelPromiseSynchronousResolve([
timedPromise(20, 'called first promise'),
timedPromise(60, 'called second promise'),
timedPromise(40, 'called third promise'),
], [
x => console.log('resolved first promise'),
x => console.log('resolved second promise'),
x => console.log('resolved third promise'),
])
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
Cheers for any help.