同步函数调用异步getMLRiskScore返回[object Promise]的解决方案咨询
同步函数调用异步函数返回
[object Promise]的解决办法 问题根源
你看到[object Promise]是因为所有异步操作的返回值都是Promise对象。哪怕你在同步函数里调用异步函数并使用.then(),整个evaluateMLRiskCategory的返回值依然是Promise——因为.then()本身就会返回一个新的Promise。控制台能打印正确结果,是因为.then()里的回调是异步执行的,但函数本身已经先返回了Promise对象。
最佳解决方法
方法1:将evaluateMLRiskCategory改为异步函数(推荐)
直接把同步函数转为异步函数,用async/await语法,代码更简洁易读:
async evaluateMLRiskCategory(...args) { try { const result = await getMLRiskScore(args); console.log('-----my result', result); return result; } catch (err) { return `An error occured: ${err}`; } }
调用这个异步函数时,必须用await或者.then()获取结果:
// 示例1:在异步函数中用await async function getRiskResult() { const riskCategory = await evaluateMLRiskCategory(/* 传入你的参数 */); // 这里直接使用riskCategory的实际值 } // 示例2:用.then()链式调用 evaluateMLRiskCategory(/* 传入你的参数 */) .then(riskCategory => { // 在这里处理结果 }) .catch(err => { // 处理错误 });
方法2:保持同步函数,但调用时处理Promise
如果无法修改evaluateMLRiskCategory的同步性质,调用它时必须手动处理返回的Promise:
// 方式1:使用.then() evaluateMLRiskCategory(/* 参数 */).then(riskResult => { // 这里拿到的是实际结果 console.log(riskResult); }).catch(error => { console.error(error); }); // 方式2:在异步函数中使用await async function useRiskResult() { const riskResult = await evaluateMLRiskCategory(/* 参数 */); console.log(riskResult); } useRiskResult();
代码优化建议
你的getMLRiskScore函数混合了await和.then(),可以统一用await语法让代码更一致:
export async function getMLRiskScore(params: any): Promise<any | null> { const mlScoringRequestPayload = { // 原payload内容保持不变 }; const url = 'http://197.248.44.228:8600/openmrs/ws/rest/v1/keml/casefindingscore'; const response = await fetch(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify(mlScoringRequestPayload), }); const result = await response.json(); // 改用await替代.then() if (result?.result?.predictions) { console.log("---y", result?.result?.predictions); const lowRiskThreshold = 0.002625179; const mediumRiskThreshold = 0.010638781; const highRiskThreshold = 0.028924102; const probability = result.result.predictions['probability(1)']; if (probability > highRiskThreshold) { return 'Client has a very high probability of a HIV positive test result. Testing is strongly recommended'; } else if (probability > mediumRiskThreshold) { return 'Client has a high probability of a HIV positive test result. Testing is strongly recommended'; } else if (probability > lowRiskThreshold) { return 'Client has a medium probability of a HIV positive test result. Testing is recommended'; } else if (probability <= lowRiskThreshold) { return 'Client has a low probability of a HIV positive test result. Testing may not be recommended'; } } return `No results found`; // 统一默认返回值,去掉冗余else }
内容的提问来源于stack exchange,提问作者CKW
相关产品推荐
相关产品推荐

