JavaScript Promise then回调中如何传递自定义参数
向Promise then回调传递自定义参数的解决方案
你当前代码中executionContext在then回调内为undefined,通常是异步执行时变量引用丢失、或上游未正确传入参数导致的,可通过以下几种方案传递自定义参数并修复问题:
方法1:临时存储上下文变量(适配所有JS环境)
先把外部传入的executionContext赋值给局部临时变量,避免异步执行期间外部变量被修改,写法:function page_refresh(executionContext) { // 提前存储原始上下文,锁死在当前作用域 const formExecutionContext = executionContext; Xrm.Navigation.openAlertDialog({ text: "Now I'll refresh page" }) .then( function (success) { // 访问临时存储的变量 const formContext = formExecutionContext.getFormContext(); formContext.data.refresh(true); }, function (error) { console.log(error.message); } ); }如果运行后
formExecutionContext还是undefined,优先检查page_refresh的调用/绑定逻辑:如果是Dynamics 365等平台的表单事件触发该函数,需要在事件处理程序配置中勾选「将执行上下文作为第一个参数传递」,否则函数收不到executionContext参数。方法2:用
bind()显式绑定自定义参数
可以用Function.prototype.bind()预先把自定义参数绑定到回调函数上,Promise调用回调时会自动带上预绑定的参数:function page_refresh(executionContext) { Xrm.Navigation.openAlertDialog({ text: "Now I'll refresh page" }) .then( // 回调参数顺序:自定义参数放前面,Promise返回值放后面 function (savedCtx, success) { const formContext = savedCtx.getFormContext(); formContext.data.refresh(true); }.bind(null, executionContext), // 预绑定第一个参数为外部传入的executionContext function (error) { console.log(error.message); } ); }方法3:ES6箭头函数简化写法
箭头函数会继承外层作用域的上下文,天然支持闭包访问外部变量,写法更简洁,适配支持ES6的运行环境:function page_refresh(executionContext) { Xrm.Navigation.openAlertDialog({ text: "Now I'll refresh page" }) .then( (success) => { const formContext = executionContext.getFormContext(); formContext.data.refresh(true); }, (error) => { console.log(error.message); } ); }
排查提醒:如果以上方案均返回
undefined,可先在page_refresh的第一行打印executionContext,确认函数本身是否正确接收到了参数,排除上游传入的问题后再排查Promise的执行逻辑。
内容的提问来源于stack exchange,提问作者stinger
相关产品推荐
相关产品推荐

