JavaScript - Promisification
JavaScript 中的 Promisification
JavaScript 中的 Promisification 是指将回调函数转换为返回 Promise 的常规函数。
将回调函数转换为 Promise 的原因是,当需要编写嵌套回调函数时,它会增加代码的复杂性。因此,您可以编写一个返回 Promise 的函数。
在 JavaScript 中,您可以将函数作为另一个称为回调函数的函数的参数传递。回调函数用于处理异步任务。
我们先来编写一个回调函数的示例。
回调函数
示例
在下面的代码中,我们将回调函数作为 getSum() 函数的最后一个参数传递。getSum() 函数在传递错误和结果和值作为参数后调用回调函数。
<html>
<body>
<div id = "output">The sum of 5 and 10 is: </div>
<script>
function getSum(p, q, callback) {
let sum = p + q;
setTimeout(() => callback(null, sum), 100);
}
getSum(5, 10, (err, sum) => { // callback function
document.getElementById("output").innerHTML += sum;
});
</script>
</body>
</html>
输出
The sum of 5 and 10 is: 15
让我们对上面示例中讨论的回调函数进行 Promis 化。
回调函数的 Promis 化
示例
让我们逐步理解以下代码。
步骤 1 − 首先,我们创建了 findSum() 函数。它以 p1、p2 和回调函数作为参数。
步骤 2 − 接下来,findSum() 函数检查 p1 和 p2 是否有效。如果没有,它会通过将错误作为参数传递来调用回调函数。
步骤 3 − 在其他情况下,它会通过将 sum 和 message 作为参数传递来调用回调函数。
步骤 4 − 接下来,我们定义了 promisifyFunc() 函数,它将函数作为 promisify 所需的参数。
步骤 5 − promisifyFunc() 函数返回该函数,该函数返回 Promise。
步骤 6 − 在 Promise 中,我们定义了 callFunc() 函数,该函数根据接收到的参数解析或拒绝 Promise。
步骤 7 − 接下来,我们将 callFunc() 函数插入到 args 数组中,并使用 call() 方法调用 func 函数,该函数作为 promisifyFunc() 的参数接收。函数。
步骤 8 − 之后,我们调用 promisifyFunc() 函数,并将返回的函数存储在 getSUmPromise() 函数中。
步骤 9 − 当执行 getSumPromise() 函数时,它会返回 Promise,您可以使用 then() 和 catch() 方法。
<html>
<body>
<div id = "output"> </div>
<script>
let output = document.getElementById("output");
const findSum = (p1, p2, callback) => {
if (!p1 || !p2) {
return callback(new Error("Missing dependencies"), null);
}
const sum = p1 + p2;
const msg = 'The sum of numbers is ' + sum;
return callback(null, sum, msg); // We call the callback function
}
function promisifyFunc(func) {
return (...args) => { // 返回一个函数
return new Promise((resolve, reject) => { // Returning a promise
// 为函数定义自定义回调
function callbackFunc(err, ...data) {
if (err) {
return reject(err)
}
return resolve(data)
}
args.push(callbackFunc); // 将回调函数添加到参数中
func.call(this, ...args); // 调用 findSum() 函数
})
}
}
const getSumPromise = promisifyFunc(findSum)
getSumPromise(5, 10)
.then((message) => {
output.innerHTML = message;
})
.catch((err) => {
output.innerHTML = err;
})
</script>
</body>
</html>
输出
15,The sum of numbers is 15
上面的代码看起来很复杂,但如果用它来处理嵌套的回调函数,管理起来就会变得简单。在这里,你可以将自定义回调函数传递给 Promise 中的特定函数。

