1

A piece of codes:

// file defined here.
return getFile.then(function _gotFile(file) { // getFile is a promise, resolved OR rejected
  // A
  // do something on file
  return file;
})
  .catch(function() {
    // B
    // do other things on file, 
    return file;
  })

In the above piece of codes, I am using promise catch to control program flow: if getFile promise resolved, do A, otherwise, do B.

Is it good practice to write codes like this?

How to rewrite the above piece of codes to avoid this? Thanks

BAE
  • 8,550
  • 22
  • 88
  • 171

1 Answers1

1

If getFile promise resolved, do A, otherwise, do B.

Actually, no. It also does B when A failed. If you really want "otherwise", then you need to use .then(…, …) instead of .then(…).catch(…). See also Correct Try...Catch Syntax Using Async/Await.

Is it good practice to write codes like this?

Yes, and no. It depends.

It is totally normal to make control flow decisions with exceptions. If something fails, it is definitely a good practice to handle the error.

On the other hand, you can overuse exceptions. Sometimes returning a boolean value or result type enum or something similar through the fulfillment case, and distinguishing it using if/else, can be much simpler.

Also, when you are using exceptions/rejections, you need to beware and use them right. JS only has catch-all, no conditional exceptions, and doing it manually is cumbersome. Still, it is usually a good practice to catch only specific kinds of errors that you actually can handle, and to rethrow others. Have a look here for an exacmple.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375