0

I am noticing that Visual Studio Code is highlighting the following function, to let me know I can make it an async function (because it returns a promise):

  const { isLoading, refetch } = useQuery(['FETCH CUSTOMERS', page], () => {
    return getCustomersList(page, 100, createQuery(filters)).then(
      ({ rows = 1, totalPages: newTotalPages = 1 }) => {
        if (totalPages !== newTotalPages) {
          setTotalPages(newTotalPages);
        }
        dispatch(loadCustomers(rows));
      }
    );
  });

But in this, case, by using then I am effectively doing the same as awaiting the promise to return before doing something with it, correct?

In other words, would converting the function to use async/await like so, make any functional different here?

  const { isLoading, refetch } = useQuery(['FETCH CUSTOMERS', page], async () => {
    return await getCustomersList(page, 100, createQuery(filters)).then(
      ({ rows = 1, totalPages: newTotalPages = 1 }) => {
        if (totalPages !== newTotalPages) {
          setTotalPages(newTotalPages);
        }
        dispatch(loadCustomers(rows));
      }
    );
  });
Muirik
  • 6,049
  • 7
  • 58
  • 116
  • 1
    As for your question of `return` vs `return await` see: [Difference between `return await promise` and `return promise`](https://stackoverflow.com/questions/38708550/difference-between-return-await-promise-and-return-promise) – pilchard Nov 08 '22 at 18:01

1 Answers1

2

The callbacks in both of your examples return undefined since you don't return anything from your then. I believe VSCode intends you to await getCustomersList, assign the result to a variable, and then handle any further logic without a then at all, so your examples are not accurate.

The async/await version would actually look like the following, which in your case would make it clear that you weren't returning anything.

const { isLoading, refetch } = useQuery(['FETCH CUSTOMERS', page], async () => {
  const customers = await getCustomersList(page, 100, createQuery(filters));
  const { rows = 1, totalPages: newTotalPages = 1 } = customers;
  if (totalPages !== newTotalPages) {
    setTotalPages(newTotalPages);
  }
  dispatch(loadCustomers(rows));

  return;
});
pilchard
  • 12,414
  • 5
  • 11
  • 23