DEV Community

Tobani Esan-George
Tobani Esan-George

Posted on

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

Top comments (0)