Skip to content

Commit 7ed61e2

Browse files
with promises
Signed-off-by: Arnav Gupta <[email protected]>
1 parent 6ea4316 commit 7ed61e2

File tree

3 files changed

+46
-15
lines changed

3 files changed

+46
-15
lines changed

Lecture11/3-file-sort/out2.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
,,,1,2,3,3,3,4,4,4,5,5,5,6,6,7,7,8,24,24,26,34,34,35,35,35,42,43,46,46,46,52,52,52,52,52,53,56,56,57,57,58,67,68,69,73,78,86,234,234,237,243,245,245,245,245,245,324,357,357,425,457,462,524,524,524,532,563,567,573,624,624,624,656,735,875,876,2346,2354,3245,4224,4624,6245,7987,9857,32345,56345,56746,56756,56789,456785

Lecture11/3-file-sort/sort-p.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const fs = require('fs').promises
2+
const os = require('os')
3+
os.EOL // instead of '\n'
4+
5+
Promise.all([
6+
fs.readFile(__dirname + '/1.txt'),
7+
fs.readFile(__dirname + '/2.txt'),
8+
fs.readFile(__dirname + '/3.txt')
9+
]).then((arr) => {
10+
let nums = []
11+
arr.forEach((fileData) => {
12+
nums = nums.concat(fileData.toString().split(os.EOL))
13+
})
14+
nums = nums.sort((a, b) => a - b)
15+
return fs.writeFile(__dirname + '/out2.txt', nums)
16+
}).then(() => {
17+
console.log('All done!')
18+
})

Lecture11/promises/promises.js

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,34 +26,46 @@ function readFile3(path) {
2626
reject(new Error('Path invalid'))
2727
}
2828
setTimeout(() => {
29-
resolve('Sample data 3')
29+
resolve()
3030
}, 3000)
3131
})
3232
}
3333

3434
function writeFile(data1, data2, data3, done) {
3535
return new Promise((resolve, reject) => {
36+
if (!data1 || !data2 || !data3) {
37+
reject(new Error('Missing data'))
38+
}
3639
setTimeout(() => {
3740
console.log('data written', [data1, data2, data3])
38-
resolve()
41+
resolve('Sample data 3')
3942
}, 2000)
4043
})
4144
}
4245

46+
4347
let errH = (err) => {
4448
if (err) console.error(err)
4549
}
4650

47-
readFile1('asdasd')
48-
.then((data1) => {
49-
readFile2('')
50-
.then((data2) => {
51-
readFile3('dgngdn')
52-
.then((data3) => {
53-
writeFile(data1, data2, data3)
54-
})
55-
.catch(errH)
56-
})
57-
.catch(errH)
58-
})
59-
.catch(errH)
51+
// readFile1('asdasd')
52+
// .then((data1) => {
53+
// readFile2('jhgjujh')
54+
// .then((data2) => {
55+
// readFile3('dgngdn')
56+
// .then((data3) => {
57+
// writeFile(data1, data2, data3)
58+
// .catch(errH)
59+
// })
60+
// .catch(errH)
61+
// })
62+
// .catch(errH)
63+
// })
64+
// .catch(errH)
65+
66+
Promise.all([
67+
readFile1('asdasd'),
68+
readFile2('adfadf'),
69+
readFile3('jgcvjhgc')
70+
]).then((arr) => writeFile(...arr))
71+
.catch(errH)

0 commit comments

Comments
 (0)