即使这与以太坊有关,但它实际上是一个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 one和this one等等)和(2)我真的被卡住了真的很感激一些帮助。
答案 0 :(得分:0)
这不起作用,因为它返回ReferenceError:未定义err。
您将err
定义为此函数的参数:
function sendContract(err, res)
与所有参数一样,它是该函数的本地作用域变量。
您尝试在此处使用该变量:
}, sendContract(err, res));
因此,您尝试调用 sendContract
将名为err
的变量从函数外部传递到同名的局部变量中功能
由于您尚未在函数外定义err
,因此会出现引用错误。
res
您遇到同样的问题,但由于err
版本首先触发,您无法看到它。
我知道这与承诺相关
不是。