0

I have my function handleRes who is exec in await.

But i want exec a function when the await is ended. Like with .then or .catch

How can i do something like this

I import this function

 const handleRes = res => {
    res
      .then(({ data }) => {
        console.log('done');
      })
      .catch((error) => {
        console.log('error');
      });
  };

Read it in this file and exec something when it end

await handleRes(res).then(() => setLoading(false));
AlexDemzz
  • 243
  • 2
  • 18

1 Answers1

4

handleRes doesn't return the promise chain, so you can't wait on its work to finish from outside of it. The solution is to modify it so that it returns the chain:

const handleRes = res => {
  return res
//^^^^^^
    .then(({ data }) => {
      console.log('done');
    })
    .catch((error) => {
      console.log('error');
    });
};

Then you can await it. In the normal case, that would like:

await handleRes(res);
setLoading(false);

...but your version using then also works.

In the normal case, you would also remove that error handler so that errors propagate along the chain and are handled by the functions calling handleRes (or the functions calling them, if they pass the chain along). With the function as shown above (with the catch), the caller has no way to know whether the operation succeeded or failed, because the catch converts the rejection into a fulfillment (with the value undefined).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Does returning res.then()... return a promise? Or should the whole res be wrapped in a new promise? – mind Aug 06 '19 at 15:45
  • 2
    @mind - Yes, the methods on promise instances (`then`, `catch`, and `finally`) all create and return promises. That's why the `catch` call in the OP's original code works; if `then` didn't return a promise, there'd be nothing for `catch` to be called on. – T.J. Crowder Aug 06 '19 at 15:47