How do you read a promise object in NextJS?

Viewed 38

I need to read a promise and do things with the data in the promise object but I am not sure how to work with it.

Below is the function I am using to initially pull the data:

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)
        })
}

Then I am placing the data into a Map, like below:

export function getAllBalances(coin, wallets) {
    let balances = new Map()

    for(const element of wallets) {

        balances.set(element.id, getBalance(coin, element.id));
    }

    return balances;
}

Everything works out smoothly and it produces the Map below: enter image description here

I need the values in the promise (i.e. 0, 0.0001, etc.) how do I extract them?


Updated with the Fix

Adding async and pulling out the values a little more in the getAllBalances function helped, see the revised function below:

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;
}
0 Answers
Related