JavaScript async/await调用仅取数组2值中1个且报未捕获Promise错误
问题根因
你遇到的报错和值为undefined的问题来自两个核心错误:
getNewestLicenseTrackingRecord没有返回异步请求的Promise对象:Xrm.WebApi.retrieveMultipleRecords本身会返回Promise,但你没有将它作为函数返回值,外层调用时无法感知异步请求的执行状态,也拿不到回调函数里返回的数组。- 异步函数调用方式错误:你没有await整个
getNewestLicenseTrackingRecord的执行结果,反而只await了未初始化返回值的第一个元素,自然无法拿到正确的两个返回值,还会触发Promise未处理的报错。
修复方案
第一步:修改getNewestLicenseTrackingRecord函数
统一使用async/await语法简化异步逻辑,同时保证返回查询结果:
async function getNewestLicenseTrackingRecord(executionContext, maId) { debugger; maId = maId.toString().replace("{", "").replace("}", ""); try { // await异步查询结果,避免嵌套回调 const result = await parent.Xrm.WebApi.retrieveMultipleRecords( "new_license", `?$select=createdon,new_licenseno,new_systemlocation&$filter=_new_maid_value eq ${maId}&$top=1&$orderby=createdon desc` ); if (result.entities.length > 0) { const record = result.entities[0]; const licenseNo = record.new_licenseno ? record.new_licenseno.toString() : ""; const systemLocation = record.new_systemlocation ? record.new_systemlocation.toString() : ""; return [licenseNo, systemLocation]; } // 无匹配记录时返回默认空值 return ["", ""]; } catch (error) { Xrm.Utility.alertDialog("查询License记录出错:" + error.message); return ["", ""]; } }
第二步:修改异步函数调用逻辑
在maCreateWin911CcsTemplate中调整调用方式,先await整个函数的执行结果再取值:
// 替换你原来的取值逻辑 const newestLtRecordSnAndLocation = await getNewestLicenseTrackingRecord(executionContext, maId); const sn = newestLtRecordSnAndLocation[0]; const sysLocation = newestLtRecordSnAndLocation[1];
额外说明
- 原代码中查询条件拼接时的
<guid>是占位符,上述修复代码已经替换为实际的maId变量,无需再手动修改。 - 不建议混用
then回调和async/await两种异步写法,统一用async/await逻辑更清晰,也更容易排查异常。
内容的提问来源于stack exchange,提问作者J.S.Orris
相关产品推荐
相关产品推荐

