Skip to content

Instantly share code, notes, and snippets.

@JanVoracek
Created November 7, 2016 14:58
Show Gist options
  • Save JanVoracek/08133b54ad7cbe22f578a8d56465c73f to your computer and use it in GitHub Desktop.
Save JanVoracek/08133b54ad7cbe22f578a8d56465c73f to your computer and use it in GitHub Desktop.
Comparison of generator vs. promise + callback
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