Created
August 26, 2023 11:42
-
-
Save Rowadz/bbb123230d3f31b4592f0abca77ac218 to your computer and use it in GitHub Desktop.
short circuit promises in Nodejs
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
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) |
also checkout this
HTTP request orchestration techniques
https://github.com/Rowadz/promise-queue-concurrency-control
https://youtube.com/playlist?list=PLM0LBHjz37LWlkONmhzkAdd2CS_HqKjep&si=AvYIXaqvGTz2V--r
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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