Promisify is a function in node utils that converts a promise function whose last parameter is a callback with two parameters: error and data
use
The usage method is as follows:
/ / before use
fs.readFile('./index.js', (err, data) => {
if(! err) {console.log(data.toString())
}
console.log(err)
})
// after using promisify
const readFile = promisify(fs.readFile)
readFile('./index.js')
.then(data= > {
console.log(data.toString())
})
.catch(err= > {
console.log('error:', err)
})
Copy the code
implementation
Let’s implement the promisify function
// const newFn = promisify(fn)
// newFn(a) will execute the Promise parameter method
function promisify(fn) {
return function(. args) {
// Return an instance of Promise
return new Promise(function(reslove, reject) {
// newFn(a) will be executed down here
// Add parameter cb => newFn(a)
args.push(function(err, data) {
if (err) {
reject(err)
} else {
reslove(data)
}
})
// This is where the function is actually executed newFn(a, cb)
fn.apply(null, args)
})
}
}
Copy the code
My front-end repository: Web-Library