2017-12-01 22 views
-2

私はethereumとweb3jsを学習し始め、Web3js上のいくつかの機能が非同期であることに気付きました。私が達成したいのは、ウォレットの口座残高を取得し、そのデータを他のものに使用することです。マイ"Promise"オブジェクトから値を取得する方法

function getAccountBalance2(address){ 
      var wei, balance 
      //address = document.getElementById("addy").value 
      return new Promise(function(resolve, reject){ 
       web3.eth.getBalance(address, function(error, wei){ 
        if(error){ 
         console.log("Error with address"); 
        }else{ 
         var balance = web3.fromWei(wei, "ether"); 
         var bal = resolve(balance); 
         //console.log(bal); 
         console.log(balance.toNumber()); 
         return balance.toNumber(); 
        } 
       }); 
      }); 
     } 

以下のコードと私は

function interTransfer(){ 
      var from, to, amount, fromWallet, toWallet 
      from = document.getElementById("from").value 
      to = document.getElementById("to").value 
      amount = document.getElementById("amount").value 

      if(isWalletValid(from) && isWalletValid(to)){ 
       fromWallet = getAccountBalance2(from); 
       toWallet = getAccountBalance2(to); 
      }else{ 
       console.log("Something is wrong") 
      } 

      console.log(fromWallet + " "+ toWallet) 
     } 

出力の下に、この関数で返された値を使用しようとしています、私は実際の値と使用を取得するにはどうすればよい

it gives a promise object

それはinterTransfer()ファンクション

+3

[非同期呼び出しからの応答を返すにはどうすればよいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-コール) – Igor

答えて

0

約束された価値を待つ必要がある。あなたは別のthenコールでこれを行う、とすることができます - 以前の1が終了するのを待つ必要があるリクエストを避けるために - 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 
} 

かを、async機能とし、awaitキーワード:

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 
} 

getBalanceコールバックのreturnは役に立たないので、rejectにはif(error)という理由があると考えてください。

+0

それは、約束事の '.then'を' async'/'await'を使って知ることさえしないことから大きく飛躍しています:p –

関連する問題