NextJS中如何读取Promise对象并提取其实际返回值
问题描述
我需要读取Promise对象并使用其中的数据,但不清楚具体的操作方法。
以下是我最初用于拉取数据的函数实现:
export async function getBalance(coin, walletId) { const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/get_balance"; return fetch(req_url, { method: 'POST', headers: { Accept: "application/json", "Content-Type": "application/json", 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify({ id: walletId, asset: coin, }) }).then(response => response.json()) .then(data => data.balance) .then((balance) => { console.log('balance for ' + walletId + ': ' + balance) return balance }).catch(error => { console.log(error) }) }
之后我通过如下代码将数据存入Map结构中:
export function getAllBalances(coin, wallets) { let balances = new Map() for(const element of wallets) { balances.set(element.id, getBalance(coin, element.id)); } return balances; }
代码运行流程正常,最终生成的Map结构如下图所示:
我需要提取Promise中包含的实际数值(例如0、0.0001等),请问该如何实现?
修复方案
getBalance是async异步函数,调用后默认返回Promise对象,原逻辑没有等待Promise解析完成就直接把结果存入Map,所以Map里存的是Promise实例而非实际的余额数值。
为getAllBalances函数添加async标识,在函数内部通过await等待Promise解析完成、拿到实际余额值之后再存入Map即可解决问题,修复后的函数代码如下:
export async function getAllBalances(coin, wallets) { let balances = new Map() console.log("getting all balances") console.log(wallets) for(const element of wallets) { console.log(element.id) await getBalance(coin, element.id).then( (balance) => { console.log(balance) balances.set(element.id, balance) } ) } console.log(balances) return balances; }
注意:调用修复后的
getAllBalances时,也需要搭配await或者.then()才能拿到最终存储了实际数值的Map结构,因为async函数本身的返回值也是Promise对象。
内容的提问来源于stack exchange,提问作者Mabel Oza
相关产品推荐
相关产品推荐

