Skip to content

Instantly share code, notes, and snippets.

@tinovyatkin
Created October 29, 2017 15:58
Show Gist options
  • Save tinovyatkin/4316e302d8419186fe3c6af3f26badff to your computer and use it in GitHub Desktop.
Save tinovyatkin/4316e302d8419186fe3c6af3f26badff to your computer and use it in GitHub Desktop.
`util.promisify` for `readline.question`
'use strict';
// Promisifies readline.question function using node native `util.promisify`
// readline.question takes one callback that returns the answer, so it need custom promisifying
const readline = require('readline');
const { promisify } = require('util');
readline.Interface.prototype.question[promisify.custom] = function(prompt) {
return new Promise(resolve =>
readline.Interface.prototype.question.call(this, prompt, resolve),
);
};
readline.Interface.prototype.questionAsync = promisify(
readline.Interface.prototype.question,
);
/* Usage example then:
(async () => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const airportCode = await rl.questionAsync(
'Enter the airport code for stats: ',
);
rl.close();
console.info('Getting stats for %s...', airportCode);
})();
*/
@tinovyatkin
Copy link
Author

Wow, that's a collection of antipatterns. Anyway, promisified version is landed in Node 16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment