2017-07-28 10 views
0

これはEthereumに関連していますが、実際はJavaScriptに関する質問です。JavaScriptでの約束を使用したときのエラー

私の目標は、契約が展開されるとそのアドレスを返すEthereum契約を展開する機能を持たせることです(謝辞:私はMistや他のオプションで展開することに興味がありません)。

function deploy(contractName, accountOwner, _gas) { 
    // Get the contract code from contracts 
    const input = fs.readFileSync('contracts/' + contractName + '.sol').toString(); 
    const output = solc.compile(input); 
    // The trailing ':' is needed otherwise it crashes 
    const bytecode = output.contracts[':' + contractName].bytecode; 
    const abi = JSON.parse(output.contracts[':' + contractName].interface); 
    const contract = web3.eth.contract(abi); 
    const contractInstance = contract.new({ 
     data: '0x' + bytecode, 
     from: accountOwner, 
     gas: _gas 
    }, sendContract(err, res)); 
    contractInstance.then(console.log(contractInstance), console.log("Failure")); 
} 

function sendContract(err, res) { 
    return new Promise((resolve, reject) => { 
     if (err) { 
      console.log(err); 
      return reject(err); 
     } else { 
      console.log("Transaction Hash: " + res.transactionHash); 
      // If we have an address property, the contract was deployed 
      if (res.address) { 
       console.log('Contract address: ' + res.address); 
      resolve(res); 
      } 
     } 
    }) 
} 

それはReferenceError: err is not definedを返すので、これは動作しません。私はそれが約束に関係していることを知っていますが、私はそれを修正する方法がわかりません。誰かがエラーに私を指摘してくださいでしたか?

私はこのような多くの質問がここにあります知っているが、私は(1)と同様に(特にthis onethis one、)約束の説明を、それらを読んでいると、(2)実際にこだわっていますし、実際にいくつかの助けをいただければ幸いです。

+3

'sendContract(err、res)'を 'contract.new'の2番目の引数として渡しています...おそらく' sendContract'を '(err、res ) '? –

+0

'console.log'sにも同じ問題があります。 – Ryan

+0

も参照https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks – Ryan

答えて

0

This isn't working because it returns ReferenceError: err is not defined.

あなたはこの関数の引数としてerrを定義します。

function sendContract(err, res) 

は、すべての引数と同じように、それはローカルでその機能に変数をスコープです。

あなたはここでその変数を使用しようとする:

}, sendContract(err, res)); 

だから、その関数内で同じ名前のローカル変数に機能外部からerrという名前の変数を渡すコールsendContractにしよう。

関数外でerrを定義していないため、参照エラーが発生します。

resと同じ問題がありますが、errが最初にトリガーするため、表示されません。


I know it's related to the promise

それはないです。

+0

返事をありがとう。だから 'sendContract(err、res)'を 'sendContract'だけに置き換えるべきですか?私はそれを試してみましたが、エラー 'TypeError:contractInstance.thenは関数ではありません。もしそうでなければ、それが働くために必要な変更を私に見せてもらえますか? – mcansado

+0

約束を 'contract.new'に渡すように見えても、約束を返すことはありません。 – Quentin

+0

おそらくあなたは[これを読んでください](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises)すべきです。 – Quentin

関連する問題