Skip to content

Commit

Permalink
docs(eslint-plugin): [no-misused-promises] improve examples (#3898)
Browse files Browse the repository at this point in the history
* Improve no-misused-promises docs

Fixes #3892

* formatting

Co-authored-by: Brad Zacher <brad.zacher@gmail.com>
  • Loading branch information
thw0rted and bradzacher committed Sep 20, 2021
1 parent ebb33ed commit 477b0c7
Showing 1 changed file with 49 additions and 16 deletions.
65 changes: 49 additions & 16 deletions packages/eslint-plugin/docs/rules/no-misused-promises.md
Expand Up @@ -23,6 +23,25 @@ while (promise) {
}
```

Examples of **correct** code with `checksConditionals: true`:

```ts
const promise = Promise.resolve('value');

// Always `await` the Promise in a conditional
if (await promise) {
// Do something
}

const val = (await promise) ? 123 : 456;

while (await promise) {
// Do something
}
```

---

Examples of **incorrect** code for this rule with `checksVoidReturn: true`:

```ts
Expand All @@ -37,37 +56,51 @@ new Promise(async (resolve, reject) => {

const eventEmitter = new EventEmitter();
eventEmitter.on('some-event', async () => {
synchronousCall();
await doSomething();
otherSynchronousCall();
});
```

Examples of **correct** code for this rule:
Examples of **correct** code with `checksVoidReturn: true`:

```ts
const promise = Promise.resolve('value');

if (await promise) {
// Do something
}

const val = (await promise) ? 123 : 456;

while (await promise) {
// Do something
}

// for-of puts `await` in outer context
for (const value of [1, 2, 3]) {
await doSomething(value);
}

// If outer context is not `async`, handle error explicitly
Promise.all(
[1, 2, 3].map(async value => {
await doSomething(value);
}),
).catch(handleError);

// Use an async IIFE wrapper
new Promise((resolve, reject) => {
// Do something
resolve();
// combine with `void` keyword to tell `no-floating-promises` rule to ignore unhandled rejection
void (async () => {
await doSomething();
resolve();
})();
});

// Name the async wrapper to call it later
const eventEmitter = new EventEmitter();
eventEmitter.on('some-event', () => {
doSomething();
const handler = async () => {
await doSomething();
otherSynchronousCall();
};

try {
synchronousCall();
} catch (err) {
handleSpecificError(err);
}

handler().catch(handleError);
});
```

Expand Down

0 comments on commit 477b0c7

Please sign in to comment.