promisify javascript code example
Example 1: promisify
const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
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);
});
};
};