Created
January 9, 2019 14:08
-
-
Save w7089/1d9ac31209325e6fb84dc7564bae41d8 to your computer and use it in GitHub Desktop.
async-promise.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const readFileAsArray = function(file, cb = () => {}) { | |
return new Promise((resolve, reject) => { | |
fs.readFile(file, function(err, data) { | |
if (err) { | |
return reject(err) | |
cb(err) | |
} | |
const lines = data.toString().trim().split('\n') | |
resolve(lines) | |
cb(null, lines) | |
}); | |
}); | |
} | |
readFileAsArray('./numbers') | |
.then(lines => { | |
const numbers = lines.map(Number); | |
const oddNumbers = numbers.filter(number => number % 2 === 1) | |
console.log('odd nums count', oddNumbers.length) | |
}) | |
.catch(console.error) | |
readFileAsArray('./numbers', (err, lines) => { | |
if (err) throw err; | |
const numbers = lines.map(Number); | |
const oddNumbers = numbers.filter(number => number % 2 === 1) | |
console.log('odd nums count', oddNumbers.length) | |
}) | |
async function countOdd() { | |
try { | |
const lines = await readFileAsArray('./numbers') | |
const numbers = lines.map(Number); | |
const oddNumbers = numbers.filter(number => number % 2 === 1) | |
console.log('odd nums count', oddNumbers.length) | |
} catch(err) { | |
console.error(err) | |
} | |
} | |
countOdd() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment