2017-07-28 27 views
0

即使這與以太坊有關,它實際上是一個JavaScript問題。在JavaScript中使用承諾的錯誤

我的目標是擁有一個部署以太坊合同的功能,一旦合同部署完畢,合同將返回其地址(旁註:我不想用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'的第二個參數的結果......也許這只是爲了'sendContract'而沒有'(err,res )'? –

+0

與'console.log'相同的問題。 – 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)); 

所以你嘗試呼叫sendContract通過一個名爲err從功能外進入該函數內部同名的局部變量的變量。

由於您尚未在函數外部定義err,因此會出現參考錯誤。

您與res有同樣的問題,但您沒有看到它,因爲err版本首先觸發。


I know it's related to the promise

它不是。

+0

感謝您的回覆。那麼我應該只用'sendContract'來代替'sendContract(err,res)'嗎?我試過,但後來我得到一個錯誤'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