你瞅啥呢

2026-03-02 hbuilderx创建的uniapp,他会自动生成一个文件uni.promisify.adaptor.js,该代码作用是什么(deepseek)

这段代码的作用是将 UniApp 中原本使用回调函数的 API 统一转换为 Promise 风格,使得开发者可以使用 .then().catch()async/await 来处理异步操作。

具体作用解析:

1. 拦截 API 返回值

returnValue (res) {
  // 判断 res 是否是一个 Promise 对象
  if (!(!!res && (typeof res === "object" || typeof res === "function") && typeof res.then === "function")) {
    return res; // 如果不是 Promise,直接返回原值
  }
  // 如果是 Promise,进行转换处理
  // ...
}

2. 转换 UniApp 特有的返回值格式

UniApp 很多 API(如 uni.requestuni.getStorage 等)原本返回的 Promise 对象会以数组形式传递结果:

// 原始的 UniApp API 使用方式
uni.request({
  url: 'https://api.example.com',
  success: (res) => {
    console.log('成功', res);
  },
  fail: (err) => {
    console.log('失败', err);
  }
});

3. 转换为标准的 Promise 格式

// 转换后可以这样使用
try {
  const [error, result] = await uni.request({
    url: 'https://api.example.com'
  });
  if (error) {
    console.error('请求失败', error);
  } else {
    console.log('请求成功', result);
  }
} catch (err) {
  console.error('异常', err);
}

转换逻辑:

return new Promise((resolve, reject) => {
  res.then((res) => {
    if (!res) return resolve(res) 
    // 关键转换:将 [error, result] 数组格式转为标准的 resolve/reject
    return res[0] ? reject(res[0]) : resolve(res[1])
  });
});

使用示例:

// 转换前
uni.getStorage({
  key: 'userInfo',
  success: (res) => {
    console.log('获取成功', res.data);
  },
  fail: (err) => {
    console.log('获取失败', err);
  }
});

// 转换后 - 使用 async/await
async function getUserInfo() {
  const [err, res] = await uni.getStorage({ key: 'userInfo' });
  if (err) {
    console.log('获取失败', err);
    return null;
  }
  return res.data;
}

// 或者使用 .then/.catch
uni.getStorage({ key: 'userInfo' })
  .then(([err, res]) => {
    if (err) throw err;
    console.log('获取成功', res.data);
  })
  .catch(err => {
    console.log('获取失败', err);
  });

这样做的目的是让异步代码更简洁、更易维护,符合现代 JavaScript 的开发习惯。

posted @ 2026-03-02 09:13  叶乘风  阅读(132)  评论(0)    收藏  举报