Created
September 22, 2018 10:32
-
-
Save diversemix/6db63808460b49200ad8d2bec0584fef to your computer and use it in GitHub Desktop.
File search example with Promise and with Async
This file contains 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
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