promisify function nodejs code example
Example 1: node js util promisify
const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat);
async function callStat() {
const stats = await stat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
Example 2: node promisify without err
function promisify(func, callbackPos) {
return (...args) => {
return new Promise((resolve) => {
const cb = (...args) => {
resolve(args);
};
args.splice(callbackPos ? callbackPos : args.length, 0, cb);
func(...args);
});
};
};
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const asyncQuestion = promisify(rl.question.bind(rl));
(async () => {
const input = (await asyncQuestion('Type something: '))[0];
console.log('You typed: ' + input);
[someOtherInput] = await asyncQuestion('Another input: ');
console.log('You typed: ' + someOtherInput);
})();