js 异步工厂函数(有回调则回调,无回调则Promise)

封装基础工厂函数

// 异步工厂函数(有回调则走回调,无回调则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) => { /* 自定义处理 */ },您可以在异步操作完成后执行自定义的处理逻辑。
这个模式使您能够根据需要选择使用默认回调函数或自定义回调函数来处理异步操作的结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值