【问题标题】:Calculate Value from JS Promise从 JS Promise 计算价值
【发布时间】:2021-12-29 00:18:28
【问题描述】:

我已经为一个变量分配了一个回调函数。然后该函数返回一个承诺,说明它已履行和价值。我希望能够返回该值并使用它来执行数学计算。

Javascript 代码:

const DollarValue = web3.eth.getBalance(address, (err, balance) =>{
    const EthValue =  web3.utils.fromWei(balance, 'ether')
    TotalEth = parseFloat(EthValue) * 4000;
    return TotalEth;
  
})

console.log(DollarValue);

在控制台中我得到以下输出。

Promise { <state>: "pending" }
​
<state>: "fulfilled"
​
<value>: "338334846022531269"

【问题讨论】:

标签: javascript asynchronous es6-promise web3js


【解决方案1】:

假设this 是您正在使用的接口,这是一个异步接口,因此您不能直接从函数或其回调返回值,因为函数将在值可用之前很久就返回。你有两个选择。要么使用你在回调中计算的 balanceTotalEth 值,要么完全跳过回调并使用它返回的承诺。

使用普通回调:

web3.eth.getBalance(address, (err, balance) => {
    if (err) {
        console.log(err);
        // do something here upon error
        return;
    }
    const EthValue =  web3.utils.fromWei(balance, 'ether')
    const TotalEth = parseFloat(EthValue) * 4000;
    console.log(TotalEth);
    
    // use TotalEth here, not outside of the callback
  
});

使用返回的承诺:

web3.eth.getBalance(address).then(balance => {
    const EthValue =  web3.utils.fromWei(balance, 'ether')
    const TotalEth = parseFloat(EthValue) * 4000;
    
    console.log(TotalEth);
    
    // use TotalEth here, not outside of the callback
}).catch(e => {
    console.log(e);
    // handle error here
});

或者,使用带有承诺的await

async function someFunction() {

    try {
        const balance = await web3.eth.getBalance(address);
        const EthValue =  web3.utils.fromWei(balance, 'ether')
        const TotalEth = parseFloat(EthValue) * 4000;
        
        console.log(TotalEth);
        
        // use TotalEth here, not outside of the callback
    } catch(e) {
        console.log(e);
        // handle error here
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 2018-02-24
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2021-08-29
    相关资源
    最近更新 更多