Forem

Tobani Esan-George
Tobani Esan-George

Posted on

3 2

Promises, on your mark... set... Go!

More often than not, we need to use promises (async/await and so on) to fetch resources from an API or server. Unfortunately, not all APIs or servers are hosted on super fast and robust systems.

So what can you do if a fetch response is an important part of loading your UI?

Race your Promises!

Promise.race() is a method on the Promise object that takes an array of promises and returns the first one to finish.

How is this useful for loading UIs?
Take a look at this example using React and React-Router-DOM...

async function getUserInfo(user) {
  const getUser = await fetch(`https://example.com/api/get_user/${user}`).json()
  return getUser;
}

async function fallBackUser() {
  let anon;
  setTimeout(()=> anon = {name: "Anonymous"}, 1000)
  return anon;
}

async function appLoader({params}) {
  const requestUser = Promise.race([getUserInfo(params.user), fallBackUser()])
  return requestUser;
}

function App() {
  const userInfo = useLoaderData()
  return (
    <h1>Username: {userInfo.name}</h2>
  )
}
Enter fullscreen mode Exit fullscreen mode

In the above example, if the server/API doesn't send a response before 1 second(1000 milliseconds) is elapsed, requestUser takes on the value returned from the fallBackUser function, and the app is rendered.

Promise.race() has many use cases and can be used to make applications faster, or avoid getting stuck.

Or just use Axios :)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay