Skip to content

Instantly share code, notes, and snippets.

@diversemix
Created September 22, 2018 10:32
Show Gist options
  • Save diversemix/6db63808460b49200ad8d2bec0584fef to your computer and use it in GitHub Desktop.
Save diversemix/6db63808460b49200ad8d2bec0584fef to your computer and use it in GitHub Desktop.
File search example with Promise and with Async
fs = require('fs')
/*
* Wrap old-style callback with promise explicitly created...
*/
const readfolderPromise = (folder) => {
if (folder === undefined) {
folder = process.cwd()
}
console.log(folder)
var promise1 = new Promise(function(resolve, reject) {
fs.readdir(folder, function (err, files) {
if (err) {
reject(err)
} else {
console.log("got files")
resolve(files)
}
})
})
return promise1
}
/*
* Wrap old-style callback with async...
*/
const readfolderAsync = async (folder) => {
if (folder === undefined) {
folder = process.cwd()
}
console.log(folder)
return await new Promise(function(resolve, reject) {
fs.readdir(folder, function (err, files) {
if (err) {
reject(err)
} else {
console.log("got files")
f = files
resolve(files)
}
})
})
}
const callWithPromise = () => {
readfolderPromise().then( (files) => {
console.log(files)
})
}
const callWithAsync = async () => {
console.log(await readfolderAsync())
}
callWithPromise()
callWithAsync()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment