TypeScript Team | 1825955 | 2018-09-26 11:46:23 -0700 | [diff] [blame] | 1 | <!-- FIXME(alexeagle): generate the docs from the sources --> |
| 2 | |
| 3 | # Don't use promises as conditionals |
| 4 | |
| 5 | Don't write conditionals like this: |
| 6 | |
| 7 | if (returnsPromise()) { |
| 8 | // stuff |
| 9 | } |
| 10 | |
| 11 | Promises are always truthy, so this assertion will never fail. Usually, the |
| 12 | intention was to match the result of the promise. If that's the case, simply add |
| 13 | an `await`. |
| 14 | |
| 15 | if (await returnsPromise()) { |
| 16 | // stuff |
| 17 | } |
| 18 | |
| 19 | ## Examples |
| 20 | |
| 21 | ### Webdriver pre-4.0 |
| 22 | |
| 23 | In the past, WebDriver had a promise manager that scheduled commands and made it |
| 24 | easy to write tests that appeared synchronous despite the fact that each command |
| 25 | was being sent asynchronously to the browser. This led to confusing behavior and |
| 26 | sometimes code like this was written: |
| 27 | |
| 28 | function isOk() { |
| 29 | see('Loading'); |
| 30 | return find('Ok').isPresent(); |
| 31 | } |
| 32 | |
| 33 | function doStuff() { |
| 34 | click('Start'); |
| 35 | if (isOk()) { |
| 36 | // Do stuff when the page says 'ok' |
| 37 | } else { |
| 38 | // Do something else if that page isn't ok |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | The return value of isOk() was a promise, but someone who took synchronicity for |
| 43 | granted would think it's a boolean. Here the if statement could never reach the |
| 44 | else block. |
| 45 | |
| 46 | ### Refactoring |
| 47 | |
| 48 | Similar mistakes can be made if the helper function goes from synchronous to an |
| 49 | async function without changing all of the callers to await it. |