How to get a value from a “Promise” object

前端 未结 1 433
离开以前
离开以前 2021-01-24 02:40

I started learning ethereum and web3js and noticed some functions on Web3js are asynchronous. What i want to achieve is get the account balance of a wallet and use the data for

1条回答
  •  孤城傲影
    2021-01-24 03:19

    You need to await the promised values. You can do this with another then call, and -- to avoid one request having to wait for the previous one to finish -- Promise.all:

    function interTransfer(){
        // ...
        promise = Promise.all([getAccountBalance2(from), getAccountBalance2(to)])
            .then(function ([fromWallet, toWallet]) {
                console.log('from wallet', fromWallet, 'to wallet', toWallet); 
            });
        // ...
        return promise; // the caller will also need to await this if it needs the values
    }
    

    Or, with an async function and the await keyword:

    function async interTransfer(){
        // ...
        [fromWallet, toWallet] = 
            await Promise.all([getAccountBalance2(from), getAccountBalance2(to)]);
        console.log('from wallet', fromWallet, 'to wallet', toWallet); 
        // ...
        return [fromWallet, toWallet]; // caller's promise now resolves with these values
    }
    

    Note that the return in the getBalance callback is useless, and you should probably call reject with a reason in the case of if(error).

    0 讨论(0)
提交回复
热议问题