uni-app promise函数.then()内条件编译失效

uni-app promise函数.then()内条件编译失效

2 回复

现在发现其实和promise函数无关,只是单纯的在methods内就会失效

更多关于uni-app promise函数.then()内条件编译失效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中,.then()内的条件编译失效是常见问题,因为条件编译指令(如#ifdef)在编译阶段处理,而Promise回调在运行时执行,此时编译已完成。

解决方案:

  1. 将条件逻辑移到.then()外部
// 定义平台相关逻辑
const platformAction = {
  H5: () => { /* H5代码 */ },
  MP-WEIXIN: () => { /* 微信小程序代码 */ }
};

somePromise()
  .then(res => {
    const action = platformAction[uni.getSystemInfoSync().platform];
    action && action();
  });
  1. 使用运行时环境判断
somePromise()
  .then(res => {
    // 使用uni.getSystemInfoSync()动态判断
    const systemInfo = uni.getSystemInfoSync();
    if (systemInfo.platform === 'h5') {
      // H5逻辑
    } else if (systemInfo.platform === 'mp-weixin') {
      // 微信小程序逻辑
    }
  });
  1. 分离平台专用方法
// 在不同平台文件中实现
// utils-h5.js
export function platformMethod() { /* H5实现 */ }

// utils-mp.js  
export function platformMethod() { /* 小程序实现 */ }

// 业务逻辑中
import { platformMethod } from '@/utils';

somePromise().then(res => {
  platformMethod();
});
回到顶部