promisify callback code example
Example 1: 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);
})();
Example 2: js promisify in browser
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);
});
};
};