Skip to content

Instantly share code, notes, and snippets.

@Rowadz
Created August 26, 2023 11:42
Show Gist options
  • Save Rowadz/bbb123230d3f31b4592f0abca77ac218 to your computer and use it in GitHub Desktop.
Save Rowadz/bbb123230d3f31b4592f0abca77ac218 to your computer and use it in GitHub Desktop.
short circuit promises in Nodejs
import axios, { AxiosResponse } from 'axios'
type TODO = {
userId: number
id: number
title: string
completed: boolean
}
const DEFAULT_TIMEOUT = 200
const DEFAULT_TODO: TODO = {
userId: 1,
id: 2,
title: 'DEFAULT_TITLE',
completed: false,
}
const fetchData = async (): Promise<AxiosResponse<TODO>> => {
await new Promise((resolve) => setTimeout(resolve, DEFAULT_TIMEOUT + 1))
return axios.get<TODO>('https://jsonplaceholder.typicode.com/todos/1')
}
const timeout = async () => {
await new Promise((resolve) => setTimeout(resolve, DEFAULT_TIMEOUT))
return Promise.reject(DEFAULT_TODO)
}
const main = async () => {
const promises = [
fetchData(),
fetchData(),
fetchData(),
fetchData(),
fetchData(),
fetchData(),
timeout(),
]
const finalData = await Promise.race(promises)
.then((response) => response.data)
.catch(() => DEFAULT_TODO)
return finalData
}
main().then(console.log)
@Rowadz
Copy link
Author

Rowadz commented Aug 26, 2023

Promise.race()
Settles when any of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race

a nice package, but it does not work with multiple promises out of the box

https://www.npmjs.com/package/opossum

@Rowadz
Copy link
Author

Rowadz commented Aug 26, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment