|
1 | 1 | 'use strict';
|
2 | 2 |
|
| 3 | +const promisify = fn => (...args) => new Promise((resolve, reject) => { |
| 4 | + args.push((err, result) => { |
| 5 | + if (err) reject(err); |
| 6 | + else resolve(result); |
| 7 | + }); |
| 8 | + fn(...args); |
| 9 | +}); |
| 10 | + |
3 | 11 | const fs = require('fs');
|
4 |
| -const promisify = require('./promisify'); |
5 | 12 |
|
6 |
| -const readFile = promisify(fs.readFile); |
| 13 | +const readFile1 = promisify(fs.readFile); |
| 14 | + |
| 15 | +readFile1('file1.txt', 'utf8') |
| 16 | + .then(data => { |
| 17 | + console.log(data.toString()); |
| 18 | + return readFile1('file2.txt', 'utf8'); |
| 19 | + }) |
| 20 | + .then(data => { |
| 21 | + console.log(data.toString()); |
| 22 | + return readFile1('file3.txt', 'utf8'); |
| 23 | + }) |
| 24 | + .then(data => { |
| 25 | + console.log(data.toString()); |
| 26 | + }) |
| 27 | + .catch(err => { |
| 28 | + console.log(err); |
| 29 | + }); |
| 30 | + |
| 31 | +const util = require('util'); |
7 | 32 |
|
8 |
| -readFile('file1.txt', 'utf8') |
| 33 | +const readFile2 = util.promisify(fs.readFile); |
| 34 | + |
| 35 | +readFile2('file1.txt', 'utf8') |
9 | 36 | .then(data => {
|
10 | 37 | console.log(data.toString());
|
11 |
| - return readFile('file2.txt', 'utf8'); |
| 38 | + return readFile2('file2.txt', 'utf8'); |
12 | 39 | })
|
13 | 40 | .then(data => {
|
14 | 41 | console.log(data.toString());
|
15 |
| - return readFile('file3.txt', 'utf8'); |
| 42 | + return readFile2('file3.txt', 'utf8'); |
16 | 43 | })
|
17 | 44 | .then(data => {
|
18 | 45 | console.log(data.toString());
|
| 46 | + }) |
| 47 | + .catch(err => { |
| 48 | + console.log(err); |
19 | 49 | });
|
0 commit comments