我已經為一個變數分配了一個回呼函式。然后該函式回傳一個承諾,說明它已完成和價值。我希望能夠回傳該值并使用它來執行數學計算。
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"
uj5u.com熱心網友回復:
假設這是您正在使用的介面,這是一個異步介面,因此您不能直接從函式或其回呼回傳值,因為函式將在值可用之前很久就回傳。你有兩個選擇。要么在回呼中使用從它計算的balanceorTotalEth值,要么完全跳過回呼并使用它回傳的承諾。
使用簡單的回呼:
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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359487.html
標籤:javascript 异步 es6-promise web3js
