Skip to content

Commit fb13dda

Browse files
authored
about util.promisify()
1 parent 0b0f630 commit fb13dda

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

README.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,3 +407,37 @@ Use ``nextTick()`` when you want to make sure that in next event loop iteration
407407
 Did you notice how **async functions** are different compared to a **promise.then**? The ``await`` keyword suspends the ``async function``, whereas the ``Promise`` body would've kept on being executed if we would've used ``.then``!
408408
409409
 Read more in the [section with code examples](https://github.com/SKindij/Asynchronous-Programming-Node.js/tree/main/codeSamples)...
410+
411+
- - -
412+
413+
 ``util.promisify()`` is utility that allows you to convert function that uses Node.js-style callback pattern into function that returns promise.\
414+
> _Node.js-style callbacks usually follow pattern of having error object as first argument and result as second argument, like this:_
415+
> > ```javascript
416+
> > function readFile(path, callback) {
417+
> > fs.readFile(path, (err, data) => {
418+
> > if (err) {
419+
> > callback(err, null);
420+
> > } else {
421+
> > callback(null, data);
422+
> > }
423+
> > });
424+
> > }
425+
> > ```
426+
> _With util.promisify(), you can convert this function into promise-based function, like this:_
427+
> > ```javascript
428+
> > const util = require('util');
429+
> > const fs = require('fs');
430+
> > // to convert fs.readFile() into promise-based function readFile
431+
> > const readFile = util.promisify(fs.readFile);
432+
> >
433+
> > async function example() {
434+
> > try {
435+
> > // to wait for data to be read from file before logging it to console
436+
> > const data = await readFile('path/to/file.txt');
437+
> > console.log(data.toString());
438+
> > } catch (err) {
439+
> > console.error(err);
440+
> > }
441+
> > }
442+
> > ```
443+

0 commit comments

Comments
 (0)