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
Copy file name to clipboardExpand all lines: 1-js/11-async/06-promisify/article.md
+8-10Lines changed: 8 additions & 10 deletions
Original file line number
Diff line number
Diff line change
@@ -2,8 +2,6 @@
2
2
3
3
Promisification -- is a long word for a simple transform. It's conversion of a function that accepts a callback into a function returning a promise.
4
4
5
-
To be more precise, we create a wrapper-function that does the same, internally calling the original one, but returns a promise.
6
-
7
5
Such transforms are often needed in real-life, as many functions and libraries are callback-based. But promises are more convenient. So it makes sense to promisify those.
8
6
9
7
For instance, we have `loadScript(src, callback)` from the chapter <info:callbacks>.
@@ -23,7 +21,7 @@ function loadScript(src, callback) {
Here we assume that the original function expects a callback with two arguments `(err, result)`. That's what we encounter most often. Then our custom callback is in exactly the right format, and `promisify` works great for such a case.
77
75
78
-
But what if the original `f` expects a callback with more arguments `callback(err, res1, res2)`?
76
+
But what if the original `f` expects a callback with more arguments `callback(err, res1, res2, ...)`?
79
77
80
-
Here's a modification of `promisify` that returns an array of multiple callback results:
78
+
Here's a more advanced version of `promisify`: if called as `promisify(f, true)`, the promise result will be an array of callback results`[res1, res2, ...]`:
81
79
82
80
```js
83
81
// promisify(f, true) to get array of results
@@ -105,7 +103,7 @@ f = promisify(f, true);
105
103
f(...).then(arrayOfResults=>..., err=>...)
106
104
```
107
105
108
-
In some cases, `err`may be absent at all: `callback(result)`, or there's something exotic in the callback format, then we can promisify such functions without using the helper, manually.
106
+
For more exotic callback formats, like those without `err` at all: `callback(result)`, we can promisify such functions without using the helper, manually.
109
107
110
108
There are also modules with a bit more flexible promisification functions, e.g. [es6-promisify](https://github.com/digitaldesignlabs/es6-promisify). In Node.js, there's a built-in `util.promisify` function for that.
0 commit comments