ES5环境下处理返回Promise或null的函数调用报错问题
解决ES5环境下getCurrentComponent返回null时的then调用错误问题
既然你在ES5环境里没法用原生Promise,而且调用getCurrentComponent().then(...)时会因为返回null报错,那我们可以通过包装函数来解决这个问题,确保每次调用后得到的都是一个带有then方法的对象,不管原函数返回的是null还是异步的thenable对象。
方案1:使用包装函数统一处理返回值
写一个简单的包装函数,把原函数的返回值转换成始终带有then方法的对象,这样就不会出现Cannot read property 'then' of null的错误了:
function safeComponentGetter(originalGetter) { return function() { var result = originalGetter(); // 返回一个模拟thenable的对象,兼容null和原有的异步结果 return { then: function(onResolved, onRejected) { if (result === null) { // 如果原函数返回null,直接调用resolve回调,传递null if (typeof onResolved === 'function') { onResolved(null); } } else { // 如果是异步thenable对象,直接转发then调用 result.then(onResolved, onRejected); } } }; }; }
使用方法
把你的getCurrentComponent用这个包装函数处理一下,之后就可以安全调用then了:
// 包装原函数 var safeGetCurrentComponent = safeComponentGetter(getCurrentComponent); // 安全调用,不管返回null还是异步结果都能处理 safeGetCurrentComponent().then(function(component) { if (component) { // 处理正常返回的组件逻辑 console.log('Got component:', component); } else { // 处理null的情况 console.log('No component returned'); } }, function(error) { // 处理原异步操作的错误 console.error('Component fetch failed:', error); });
方案2:每次调用前手动判断(适合单次调用场景)
如果你只是偶尔调用一次,不想写包装函数,也可以直接在调用时先判断返回值是否为null:
var componentResult = getCurrentComponent(); if (componentResult !== null) { componentResult.then(function(component) { // 处理组件逻辑 }, function(error) { // 处理错误 }); } else { // 直接处理null的情况,比如执行原本then里的回调并传递null handleComponent(null); }
这个写法更直接,但如果需要多次调用getCurrentComponent,重复写判断会比较繁琐,不如包装函数省心。
关键思路解释
核心就是确保调用后得到的对象始终有then方法:
- 当原函数返回null时,我们自己模拟一个带有
then方法的对象,直接同步调用resolve回调; - 当原函数返回异步thenable对象时,直接转发
then调用,保留原有的异步逻辑; - 完全基于ES5语法,不需要依赖任何Promise polyfill或者ES6+特性。
内容的提问来源于stack exchange,提问作者Renaud is Not Bill Gates
相关产品推荐
相关产品推荐

