Completely agree, so much so, I thought promisify would be an interesting function to look into
The implementation could be as follows.
Longform with breakdown
// Promisify is a wrapper, that takes a 'given function'
// and returns another function which when invoked will return a promise.
// The promise initiates a call to the previously 'given function' passing in arguments and
// a callback with set parameters (error, /* and */ value)
// If the callback is given a first argument which evaluates to 'true'
// — in other words an error — the promise is rejected with that argument
// Otherwise if the first argument evaluates to 'false'
// the second argument 'value' is resolved — 'Happy Days'
function promisify (func) {
return function(...args) {
return new Promise(function(resolve, reject){
func(...args, function(error, value) {
if (error) reject(error)
else resolve(value)
})
})
}
}
In shortform
const promisify = (fn) => (...args) =>
new Promise((resolve, reject) => {
fn(...args, (error, value) => (error ? reject(error) : resolve(value)))
})
Usage example I am basing on the examples on https://javascript.info/promisify, but with the more generic promisify above.
./scripts/dummy-script.js
GlobalData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
index.html
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Promisify</title>
</head>
<body>
<script>
const promisify = (fn) => (...args) =>
new Promise((resolve, reject) => {
fn(...args, (error, value) => (error ? reject(error) : resolve(value)))
})
// example taken from https://javascript.info/promisify
const loadScript = (src, callback) => {
const script = document.createElement('script')
script.src = src
script.onload = () => callback(null, script)
script.onerror = () => callback(new Error(`Script load error for ${src}`))
document.head.append(script)
}
// promisify loadScript
const loadScriptPromisified = promisify(loadScript)
// successfully resolve
loadScriptPromisified('./scripts/dummy-script.js')
.then(script => console.log(GlobalData)) // [1, 2, 3, ...9, 10]
.catch(console.log)
// typo in path
loadScriptPromisified('./scripts/dummyScrip.js')
.then(script => console.log(GlobalData))
.catch(console.log) // Error: Script load error for ./scripts/dummyScrip.js
</script>
</body>
</html>