From 477b0c72749f60f18d9d0b47a8e25da4241e7641 Mon Sep 17 00:00:00 2001 From: James Bromwell <943160+thw0rted@users.noreply.github.com> Date: Tue, 21 Sep 2021 01:43:14 +0200 Subject: [PATCH] docs(eslint-plugin): [no-misused-promises] improve examples (#3898) * Improve no-misused-promises docs Fixes #3892 * formatting Co-authored-by: Brad Zacher --- .../docs/rules/no-misused-promises.md | 65 ++++++++++++++----- 1 file changed, 49 insertions(+), 16 deletions(-) diff --git a/packages/eslint-plugin/docs/rules/no-misused-promises.md b/packages/eslint-plugin/docs/rules/no-misused-promises.md index 6a4c2a55792..0d908890eda 100644 --- a/packages/eslint-plugin/docs/rules/no-misused-promises.md +++ b/packages/eslint-plugin/docs/rules/no-misused-promises.md @@ -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 @@ -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); }); ```