Skip to content

Instantly share code, notes, and snippets.

@jaredLunde
Last active April 10, 2019 23:11
Show Gist options
  • Save jaredLunde/3023dd7713b0ddc6be29d45f9bb7db4f to your computer and use it in GitHub Desktop.
Save jaredLunde/3023dd7713b0ddc6be29d45f9bb7db4f to your computer and use it in GitHub Desktop.
const resolveSynchronously = promises => {
if (promises.length > 0) {
const [next, resolve] = promises[0]
next.then(value => {
resolve(value)
// shift must be performed here to avoid accidentally creating a situation where
// pendingUpdates length === 1, allowing for subsequent requests to potentially
// resolve first
promises.shift()
resolveSynchronously(promises)
})
}
}
const createFetchContext = () => {
const pendingUpdates = []
return (url, opt) => new Promise(resolve => {
pendingUpdates.push([fetch(url, opt), resolve])
// if this is the only pending query, go ahead and resolve it
if (pendingUpdates.length === 1) {
resolveSynchronously(pendingUpdates)
}
})
}
// usage
const fetchSync = createFetchContext()
// these will resolve synchronously
fetchSync('https://jsonplaceholder.typicode.com/todos/1').then(r => console.log('Resolved 1', r))
fetchSync('https://jsonplaceholder.typicode.com/todos/2').then(r => console.log('Resolved 2', r))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment