【问题标题】:Callback isn't triggered node.js回调未触发 node.js
【发布时间】:2020-08-08 16:55:09
【问题描述】:

我可能在这里遗漏了一些回调和承诺的概念,但我找不到我的代码工作的方法。

这里是:

var tx;

web3.eth.getBlock(6339515, function(err, result){
    for(var i = 0; i <= result.transactions.length; i++){
        tx = result.transactions[i];
        getInputTransaction(tx)
        .then(function() {} )
        .catch(function(error) {
            console.log('error: \n' + error);
        });
    }
})

async function getInputTransaction(tx) {
    web3.eth.getTransaction(tx, function(err, cb){
        console.log('got here');
        let decodeInput = web3.utils.hexToAscii(cb.input);
        decodeInput = decodeInput.split("_").pop();
        if(!err){
            console.log(cb);
            console.log('\nInput decoded: ' + '\u001b[1;32m' + decodeInput + '\u001b[0m');
        }else{
            console.log('error: ' + error);
    }}
    )
}

基本上,我想获取第一种方法的结果回调以获取每个索引值,并将其传递给第二种方法以扫描该值,在这种情况下是一个以太坊交易来获取输入值。问题是没有触发名为“cb”的回调。

各自的文件:

getBlock getTransaction

我在这里错过了什么?

【问题讨论】:

    标签: node.js promise callback ethereum web3js


    【解决方案1】:

    我不知道为什么它没有被触发。但是一些提示。调用 web3 函数时使用新的await 语法,因此无需编写回调,代码线性且易于分析。

    使用 TypeScript 而不是 JavaScript,因为 TypeScript 编译器可能不允许您编译导致此类错误情况的代码。

    另外,我认为这条线可能会丢失return

    web3.eth.getTransaction(tx, function(err, cb)
    

    【讨论】:

    • 简单的return web3.eth.getTransaction() 将不起作用,除非web3.eth.getTransaction() 返回 Promise。 web3.eth.getTransaction() 很可能需要为 promisified
    【解决方案2】:

    知道了。

    问题是我没有确保getInputTransaction中的参数cb

    let decodeInput = web3.utils.hexToAscii(cb.input) 之前使用if(cb &amp;&amp; cb.input != undefined) 效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2019-04-18
      相关资源
      最近更新 更多