Skip to content

Instantly share code, notes, and snippets.

@goldhand
Created November 18, 2016 07:47
Show Gist options
  • Save goldhand/3b4c4e592ca4df4b951f85550c19d1ba to your computer and use it in GitHub Desktop.
Save goldhand/3b4c4e592ca4df4b951f85550c19d1ba to your computer and use it in GitHub Desktop.
Compare Async / Promise / Callback hell javascript code examples of same end
/**
* fsExists promise
* @param {string} fp - filepath to check exists
* @returns {Promise} fsExists
*/
const fsExists = (fp) => new Promise(
resolve => fs.access(fp, err => resolve(!err))
);
const filepath = path.resolve(__dirname, 'tmp/service-worker.js');
const compiler = webpack(webpackConfig());
const plugin = new SWPrecacheWebpackPlugin({filepath});
plugin.apply(compiler);
/* Callback hell version */
test.cb('#writeServiceWorker(comiler, config)', t => {
t.plan(2);
fs.access(
filepath,
shouldNotExist => {
t.falsy(!shouldNotExist, 'service-worker should not exist');
plugin.writeServiceWorker(compiler, plugin.options).then(() => {
fs.access(
filepath,
shouldExist => {
t.truthy(!shouldExist, 'service-worker should exist');
t.end();
},
);
});
}
);
});
/* Promise version */
test('#writeServiceWorker(comiler, config)', t => {
t.plan(2);
return fsExists(filepath)
.then(shouldNotExist => {
t.falsy(shouldNotExist, 'service-worker should not exist yet');
})
.then(() => plugin.writeServiceWorker(compiler, plugin.options))
.then(() => fsExists(filepath))
.then(shouldExist => {
t.truthy(shouldExist, 'service-worker should exist');
});
});
/* Async/await version */
test('#writeServiceWorker(comiler, config)', async t => {
t.plan(2);
t.falsy(await fsExists(filepath), 'service-worker should not exist yet');
await plugin.writeServiceWorker(compiler, plugin.options);
t.truthy(await fsExists(filepath), 'service-worker should exist');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment