You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Avoid calling `cb()` inside of a `then()` or `catch()` (no-callback-in-promise)
2
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. It also can be confusing to mix paradigms.
3
+
As a general rule, callbacks should never be directly invoked inside a
4
+
[Promise.prototype.then()] or [Promise.prototype.catch()] method. That's because
5
+
your callback may be unintentionally be invoked twice. It also can be confusing
6
+
to mix paradigms.
4
7
5
8
Take the following example:
6
9
7
10
```js
8
11
functioncallback(err, data) {
9
-
console.log("Callback got called with:", err, data);
10
-
thrownewError("My error");
12
+
console.log('Callback got called with:', err, data)
13
+
thrownewError('My error')
11
14
}
12
15
13
16
// note: passing `err.message` for demo purposes, normally you would pass `err`
14
17
Promise.resolve()
15
-
.then(() =>callback(null, "data"))
16
-
.catch(err=>callback(err.message, null));
18
+
.then(() =>callback(null, 'data'))
19
+
.catch((err)=>callback(err.message, null))
17
20
```
18
21
19
22
If you run this example, your output will look like the following:
@@ -25,20 +28,22 @@ Callback got called with: My error null
25
28
26
29
**How to fix it?**
27
30
28
-
Ensure that your callback invocations are wrapped by a deferred execution function such as:
31
+
Ensure that your callback invocations are wrapped by a deferred execution
32
+
function such as:
33
+
29
34
-[setImmediate()] or [process.nextTick()]: for Node.js.
@@ -47,11 +52,19 @@ Your output will now look like the following:
47
52
Callback got called with:null data
48
53
```
49
54
50
-
Finally, if your callbacks have a Node.js signature (i.e. `callback(err, data)`), consider using [util.promsify] for promisifying your callback code instead of combining the approaches.
55
+
Finally, if your callbacks have a Node.js signature (i.e.
56
+
`callback(err, data)`), consider using [util.promsify] for promisifying your
57
+
callback code instead of combining the approaches.
0 commit comments