Skip to content

Instantly share code, notes, and snippets.

@akumbhani66
Last active January 1, 2019 12:15
Show Gist options
  • Save akumbhani66/c2600ca9c92af326242b1907e074027f to your computer and use it in GitHub Desktop.
Save akumbhani66/c2600ca9c92af326242b1907e074027f to your computer and use it in GitHub Desktop.
Basic of async.
const fs = require('fs')
function myReaddir() {
return new Promise((resolve, reject) => {
fs.readdir("./aaa", function(err, files){
if(err) {
reject(err);
} else {
resolve(files);
}
})
})
}
function myReadFile(file) {
console.log("....", file);
return new Promise((resolve, reject) => {
fs.readFile("./aaa/" + file, function(err, data) {
if(err) reject(err);
else resolve(data);
})
})
}
//myReaddir().then((data)=> {
// myReadFile(data[0]).then((content)=>{
// console.log("content:", content.toString());
// })
//}).catch((err) => {
// console.log(">>>", err);
//});
async function readFiles() {
let files;
try {
files = await myReaddir();
} catch(err) {
console.log("Error:", err);
}
console.log(">>>", files);
let fileContent;
try {
fileContent = await myReadFile(files[0]);
} catch(err) {
throw err;
}
console.log("File content:", fileContent.toString());
}
readFiles();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment