Created
October 29, 2017 15:58
-
-
Save tinovyatkin/4316e302d8419186fe3c6af3f26badff to your computer and use it in GitHub Desktop.
`util.promisify` for `readline.question`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
})(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, that's a collection of antipatterns. Anyway, promisified version is landed in Node 16