Created
November 12, 2021 13:25
-
-
Save lifeart/9c1fff561d19feecde4fc5550357fcd6 to your computer and use it in GitHub Desktop.
Promise queue
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
async function request() { | |
const PromiseState = new WeakMap(); | |
const resolveTimers = new Array(10).fill(null).map(() => Math.random() * 10000); | |
const rejectTImers = new Array(10).fill(null).map(() => Math.random() * 10000); | |
const promiseArgs = resolveTimers.map((_, i) => [resolveTimers[i], rejectTImers[i]]); | |
let promises = promiseArgs.map(([resolveTimeout, rejectTimeout]) => { | |
const promiseInfo = { | |
data: null, state: 'PENDING' | |
} | |
const p = new Promise((resolve, reject) => { | |
promiseInfo.reject = reject; | |
promiseInfo.resolve = resolve; | |
setTimeout(() => { | |
console.log('resolve'); | |
promiseInfo.state = 'RESOLVED'; | |
const data = 42; | |
promiseInfo.data = data; | |
// here is resolve logic | |
resolve(data); | |
}, resolveTimeout); | |
setTimeout(() => { | |
console.log('reject'); | |
promiseInfo.state = 'REJECTED'; | |
// reject internally if needed | |
reject('internal reject'); | |
}, rejectTimeout); | |
}); | |
p.catch(e => { | |
console.log(e, 'promise rejected'); | |
}); | |
PromiseState.set(p, promiseInfo); | |
return p; | |
}); | |
let result = null; | |
let rejectPromises = () => { | |
promises.map(p => { | |
const pState = PromiseState.get(p); | |
if (pState.state === 'PENDING') { | |
PromiseState.get(p).reject('outdated'); | |
} | |
}); | |
} | |
let isCorrectData = (data) => { | |
return data === 42; | |
} | |
while (promises.length) { | |
await new Promise((resolve) => setTimeout(resolve)); | |
const resolvedPromise = promises.find(p => PromiseState.get(p).state === 'RESOLVED'); | |
if (resolvedPromise) { | |
promises = promises.filter(p => p !== resolvedPromise); | |
const data = PromiseState.get(resolvedPromise).data; | |
if (isCorrectData(data)) { | |
rejectPromises(); | |
console.log('all done!', promises); | |
result = data; | |
break; | |
} | |
} | |
promises.filter(p => PromiseState.get(p).state !== 'REJECTED'); | |
} | |
console.log('do some logic with result:', result); | |
} | |
request(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment