blob: 61c6891fed3c6c1ae14da750423dd5c01475b475 [file] [log] [blame] [view]
TypeScript Team18259552018-09-26 11:46:23 -07001<!-- FIXME(alexeagle): generate the docs from the sources -->
2
3# Don't use promises as conditionals
4
5Don't write conditionals like this:
6
7 if (returnsPromise()) {
8 // stuff
9 }
10
11Promises are always truthy, so this assertion will never fail. Usually, the
12intention was to match the result of the promise. If that's the case, simply add
13an `await`.
14
15 if (await returnsPromise()) {
16 // stuff
17 }
18
19## Examples
20
21### Webdriver pre-4.0
22
23In the past, WebDriver had a promise manager that scheduled commands and made it
24easy to write tests that appeared synchronous despite the fact that each command
25was being sent asynchronously to the browser. This led to confusing behavior and
26sometimes 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
42The return value of isOk() was a promise, but someone who took synchronicity for
43granted would think it's a boolean. Here the if statement could never reach the
44else block.
45
46### Refactoring
47
48Similar mistakes can be made if the helper function goes from synchronous to an
49async function without changing all of the callers to await it.