What's the best way to write a series of AJAX calls?

When a user presses a button in my App, I want to make a series of AJAX calls. In JavaScript, it might looks something like

async function submit() {
  const fooData = await fetch('https://example.com/foo')
  const [barData, bazData] = await Promise.all(
    fetch(`https://example.com/bar/${fooData.barID}`),
    fetch(`https://example.com/baz/${fooData.bazID}`),
  )

  return Object.assign(fooData, {
    bar: barData,
    baz: bazData,
  })

I can think of a couple ways to do this:

  1. Three Queries: getFoo, getBar, and getBaz. getFoo is triggered by the button click. getBar and getBaz are both triggered by getFoo on success. I might use a Transformer to combine get{Foo,Bar,Baz}.data after they’re all finished.
  2. One getFoo query plus asynchronous code in its on-success transformer to fetch the Bar and Baz data. Can I even call fetch in a Transformer?

Hey @jamesarosen! Good question - the answer depends on the kind of data you’re working with and your preference. I’m guessing you’ve made some progress since this post (sorry for the delay) - but both of these methods you’ve outlined should work. You can indeed call fetch in a Transformer, like so:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

If you plan on using the other AJAX calls across your app, I’d separate them into multiple queries. If not, it’s probably going to be easier to chain them in a single query.

1 Like