Skip to content

Instantly share code, notes, and snippets.

@JamesTheHacker
Last active September 27, 2017 20:51
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 JamesTheHacker/f7839ad4969072ecba042b9fb366e3b0 to your computer and use it in GitHub Desktop.
Save JamesTheHacker/f7839ad4969072ecba042b9fb366e3b0 to your computer and use it in GitHub Desktop.
Some demo files I am using in a Medium article I write on NodeJS's util.promisify()
node promisify.js
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
[Error]: Could not wait any longer!
node promisify.js
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Congratulations, you have finished waiting.
const util = require('util');
// Here we use util.promisify to convert the function to a promise
const waitAsync = util.promisify(wait);
//And here we use the promisified function. Cool huh?
waitAsync(1000)
.then(data => console.log(data))
.catch(err => console.error(`[Error]: ${err}`));
// Calling wait and passing a callback
wait(1000, (err, data) => {
// Did the function return an error?
if (err) throw new Error(err);
// Output the data
console.log(data);
});
// This function waits for an unknown amount of time
const wait = (delay, callback) => {
// setInterval returns an ID. We need this to stop the timer
const id = setInterval(() => {
// Generate a random number between 0 and 1
const rand = Math.random();
if (rand > 0.95) {
// Call the call back function. Note the first parameter is an error
callback(null, 'Congratulations, you have finished waiting.');
// Stop the timer
clearInterval(id);
} else if (rand < 0.01) {
// Call the callback function. Note we're setting an error now
callback('Could not wait any longer!', null);
// Stop the timer
clearInterval(id);
} else {
// Print to stdouts
console.log('Waiting ...');
}
}, Number(delay));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment