Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Last active February 10, 2019 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BananaAcid/7ff43ecc26673da3fa64d94b80ab22a4 to your computer and use it in GitHub Desktop.
Save BananaAcid/7ff43ecc26673da3fa64d94b80ab22a4 to your computer and use it in GitHub Desktop.
#!/bin/sh
':' //; exec "`command -v node`" "--experimental-modules" "--no-warnings" "$0" "$@"
import fsOrig from 'fs'; const fs = fsOrig.promises;
import path from 'path';
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// "main loop" ... a promise closure to enable await.
(async () => {
const sPath = process.cwd();
console.log('processing ...');
// async getting all filenames
let files = await fs.readdir(sPath);
// kick off all tasks async, and collect their promises
let tasks = files.map( async file => {
// filter `.` files (hidden)
if (file[0] === '.') return;
// reconstruct the full file path
let fullPath = path.resolve(sPath, file);
// artificial wait - mind: all tasks are in parallel, they end at the same time + a few nano secs (not after each other)
// so the ending time is about 1300ms, not `files.length * 1300`
await delay(1300);
console.log(fullPath);
});
// wait for all tasks to finish
await Promise.all(tasks);
console.log('done.');
})().catch(console.error);
{
"name": "promise_test",
"version": "1.0.0",
"bin": "0_promise_test.mjs"
}

usage

get the files

  • git clone https://gist.github.com/BananaAcid/7ff43ecc26673da3fa64d94b80ab22a4 .
  • npm i gist:7ff43ecc26673da3fa64d94b80ab22a4 && cd node_modules/promise_test/

run the file

  • ./0_promise_test.mjs (has a shebang, you might want to chmod +x 0_promise_test.mjs to mark it as executable)
  • node --experimental-modules 0_promise_test.mjs
  • npm i esm && node -r esm 0_promise_test.mjs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment