Promisification is a long keyword for a simple transformation. It's the conversion of a function that accepts a callback to a function that returns a promise.
Such transformation are often required in real-life, as many function and libraries are callback-based. But promises are more convenient, so it makes sense to promisify them.
CALLBACK FUNCTION
function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;
script.onload = () => callback(null, script);
script.onerror = () => callback(new Error(`Script error for ${src}`));
document.head.append(script);
}
//usage
loadScript('path/script.js', (err, script) => {...})
Promisify
The new loadScriptPromise(src)
function achieves the same result, but it accepts only src (no callback) and returns a promise.
Promise function -
let loadScriptPrommise = function(src) {
return new Promise((resolve,reject) => {
loadScript(src, (err, script) => {
if (err) reject(err)
else esolve(script);
});
})
}
//usage
loadScriptPromise('path/script.js').then(...)
Let's promisify
Now loadScriptPromise
fits well in promise-based code. As we can see, it delegates all the work to the original loadScript, providing its own callback that translates to promise resolve/reject.
In practice we'll probably need to promisify many functions, so it makes sense to use a helper. We'll call t pomisify(f): it accepts a to-promisify function f and returns a wrapper function.
That wrapper does the same as in the code above: ;returns a promise an passes the call to original f, tracking the result in a custom callback.
function promisify(f) {
return function (...args) {
// return a wrapper function
return new Promise((resolve, reject) => {
function callback(err, result) {
// our cusotm callback for f
if (err) {
reject (err);
} else {
resolve(result);
}
}
args.push(callback);
//append our custom callback
// to the end of f arguments
f.call(this, ...args);
// call the original function
});
};
};
// usage:
let loadScriptPromise = promisify(loadScript);
loadScriptPromise(...).then(...);
Removal.AI - [SPONSOR]
Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.
- ✅ Drag & Drop Multiple Images
- ✅ Optimize Product Images
- ✅ Select Your Background
- ✅ Set Your Output Size
- ✅ Exceptional Results
Visit -> Removal AI