callback.js
const getDataFromFile = function (filePath, callback) {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
callback(err, null)
}
else {
callback(null, data)
}
})
};
promiseConstructor.js
const getDataFromFilePromise = filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
};
basicChaining.js
const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');
const readAllUsersChaining = () => {
return getDataFromFilePromise(user1Path)
.then((user1) => {
return getDataFromFilePromise(user2Path).then((user2) => {
return '[' + user1 + ',' + user2 + ']'
})
})
.then((ans) => JSON.parse(ans))
}
promiseAll.js
const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');
const readAllUsers = () => {
return Promise.all([getDataFromFilePromise(user1Path), getDataFromFilePromise(user2Path)])
.then(([user1, user2]) => {
return '[' + user1 + ',' + user2 + ']'
})
.then((ans) => {
return JSON.parse(ans)
})
}
asyncAwait.js
const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');
const readAllUsersAsyncAwait = async () => {
let ans = []
const user1 = await getDataFromFilePromise(user1Path)
const user2 = await getDataFromFilePromise(user2Path)
ans.push(JSON.parse(user1), JSON.parse(user2))
return ans
}