DEV Community

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 :)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay