Created
November 7, 2016 14:58
-
-
Save JanVoracek/08133b54ad7cbe22f578a8d56465c73f to your computer and use it in GitHub Desktop.
Comparison of generator vs. promise + callback
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
import * as rx from "rxjs"; | |
import * as fs from "fs-promise"; | |
import * as path from "path"; | |
function readdir(dir) { | |
return rx.Observable.create((observer: rx.Observer<string>) => { | |
fs.readdir(dir).then(async files => { | |
for (const file of files) { | |
let fullPath = path.join(dir, file); | |
let stat = await fs.stat(fullPath); | |
if (stat.isDirectory()) { | |
await new Promise(resolve => readdir(fullPath).subscribe(file => observer.next(file), e => observer.error(e), resolve)); | |
} else { | |
observer.next(fullPath); | |
} | |
} | |
observer.complete(); | |
}); | |
}); | |
} | |
async function readdirPromise(dir: string, fileCallback: (filename: string) => void) { | |
return new Promise(resolve => { | |
fs.readdir(dir).then(async files => { | |
for (const file of files) { | |
let fullPath = path.join(dir, file); | |
let stat = await fs.stat(fullPath); | |
if (stat.isDirectory()) { | |
await readdirPromise(fullPath, fileCallback); | |
} else { | |
fileCallback(fullPath); | |
} | |
} | |
resolve(); | |
}); | |
}); | |
} | |
readdir('/tmp/tree').subscribe( | |
file => console.log(file), | |
err => console.error(err), | |
() => console.log('Done') | |
); | |
readdirPromise('/tmp/tree', file => console.log(file)).then( | |
() => console.log('Done') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment