封装基础工厂函数
// 异步工厂函数(有回调则走回调,无回调则promise输出)
function asyncFactory(innerBusinessLogic, customCallback) {
return new Promise((resolve, reject) => {
// 在内部执行业务逻辑
innerBusinessLogic(resolve, reject);
})
.then((data) => (customCallback && customCallback(true, data)) || data)
.catch((err) => {
return customCallback ? customCallback(false, err) : Promise.reject(err);
});
}
使用案例
// 定义一个新函数,使用公共基础函数
function test(callback) {
return asyncFactory((resolve, reject) => {
// 内部业务的一些代码
// 例如:模拟异步操作
setTimeout(function () {
let randomValue = parseInt(Math.random() * 10)
if (randomValue % 2 == 0) {
resolve(randomValue);
} else {
reject(randomValue);
}
}, 1000);
}, callback);
}
// 使用案例
// 1. 使用默认回调函数
test()
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
// 2. 使用自定义回调函数
test((status, data) => {
if (status) {
console.log("Custom Success:", data);
} else {
console.error("Custom Error:", data);
}
});
在示例中,我们首先定义了 test 函数,它使用了您的 asyncFactory 函数来执行模拟的异步操作。您可以看到两种使用方式:
默认回调函数:使用 test() 来执行异步操作,然后使用 .then() 和 .catch() 处理成功和失败的情况。
自定义回调函数:通过传递回调函数 (status, data) => { /* 自定义处理 */ },您可以在异步操作完成后执行自定义的处理逻辑。
这个模式使您能够根据需要选择使用默认回调函数或自定义回调函数来处理异步操作的结果。