|
1 |
| -# Avoid calling `cb()` inside of a `then()` (use [nodeify][] instead) (no-callback-in-promise) |
| 1 | +# Avoid calling `cb()` inside of a `then()` or `catch()` (no-callback-in-promise) |
| 2 | + |
| 3 | +As a general rule, callbacks should never be directly invoked inside a [Promise.prototype.then()] or [Promise.prototype.catch()] method. That's because your callback may be unintentionally be invoked twice. Take the following example: |
| 4 | + |
| 5 | +```js |
| 6 | +function callback(err, data) { |
| 7 | + console.log("Callback got called with:", err, data); |
| 8 | + throw new Error("My error"); |
| 9 | +} |
| 10 | + |
| 11 | +// note: passing `err.message` for demo purposes, normally you would pass `err` |
| 12 | +Promise.resolve() |
| 13 | + .then(() => callback(null, "data")) |
| 14 | + .catch(err => callback(err.message, null)); |
| 15 | +``` |
| 16 | + |
| 17 | +If you run this example, your output will look like the following: |
| 18 | + |
| 19 | +``` |
| 20 | +Callback got called with: null data |
| 21 | +Callback got called with: My error null |
| 22 | +``` |
| 23 | + |
| 24 | +**How to fix it?** |
| 25 | + |
| 26 | +Ensure that your callback invocations are wrapped by a deferred execution function such as: |
| 27 | +- [setImmediate()] or [process.nextTick()]: for Node.js. |
| 28 | +- [setTimeout()]: for Browsers and Node.js. |
| 29 | + |
| 30 | +```js |
| 31 | +// node.js |
| 32 | +Promise.resolve() |
| 33 | + .then(() => setImmediate(() => callback(null, "data"))) |
| 34 | + .catch(err => setImmediate(() => callback(err.message, null))); |
| 35 | + |
| 36 | +// node.js and browsers |
| 37 | +Promise.resolve() |
| 38 | + .then(() => setTimeout(() => callback(null, "data"), 0)) |
| 39 | + .catch(err => setTimeout(() => callback(err.message, null), 0)); |
| 40 | +``` |
| 41 | + |
| 42 | +Your output will now look like the following: |
| 43 | + |
| 44 | +```js |
| 45 | +Callback got called with: null data |
| 46 | +``` |
| 47 | + |
| 48 | +Finally, if your callbacks have a Node.js signature (i.e. `callback(err, data)`), consider using [nodeify] for simplifying your code. |
2 | 49 |
|
3 | 50 | [nodeify]: https://www.npmjs.com/package/nodeify
|
| 51 | +[Promise.prototype.then()]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then |
| 52 | +[Promise.prototype.catch()]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch |
| 53 | +[setImmediate()]: https://nodejs.org/docs/latest-v14.x/api/timers.html#timers_setimmediate_callback_args |
| 54 | +[process.nextTick()]: https://nodejs.org/docs/latest-v14.x/api/process.html#process_process_nexttick_callback_args |
| 55 | +[setTimeout()]: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout |
0 commit comments