JS中如何将fetch API返回的Promise结果用于另一函数的if判断中
解决方案
你编写的test()函数返回的是Promise异步对象,无法直接同步读取内部的[[PromiseResult]]值,必须通过异步回调的方式获取结果后,再代入到判断逻辑中,以下是两种可直接使用的实现方案:
方案1:使用then链式调用处理异步逻辑
function main(){ // 先调用test获取汇率,拿到结果后再执行接口请求和判断逻辑 test().then(dashUsdRate => { fetch(txs_api).then(response => response.json()).then(function(data) { var amount = data.txs[0].vout[1].value; // 注意浮点数比较不要直接用==,避免精度误差导致判断失败 if(Math.abs(amount - dashUsdRate) < 0.0001){ // SUCCESS! $('#modal').modal('hide'); console.log('requests stopped'); clearInterval(interval); } }) }) }
方案2:使用async/await语法简化异步代码(可读性更高)
async function main(){ // 等待test异步执行完成拿到汇率值 const dashUsdRate = await test(); const txsRes = await fetch(txs_api); const data = await txsRes.json(); var amount = data.txs[0].vout[1].value; if(Math.abs(amount - dashUsdRate) < 0.0001){ // SUCCESS! $('#modal').modal('hide'); console.log('requests stopped'); clearInterval(interval); } }
- 补充说明:因为汇率是浮点数值,直接用
==判断很容易因为精度问题出现逻辑错误,推荐用两个值的差值小于极小阈值的方式判断相等。
内容的提问来源于stack exchange,提问作者Gass
相关产品推荐
相关产品推荐

