Home > Back-end >  Using `.then` vs async/await functional difference in example
Using `.then` vs async/await functional difference in example

Time:11-09

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));
      }
    );
  });

CodePudding user response:

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;
});
  • Related