node.js - 如何从 node.js 应用程序永久监听智能合约中的事件?

标签 node.js events solidity smartcontracts web3js

我有一个具有以下代码的 Node js 应用程序:

contract.getPastEvents('RequestCreated', function (error, event) { console.log(event); })
        .then(function (events) {
            console.log(events); 
        })

运行 Node 后,我得到一个空数组。

我的期望是在智能合约中的事件发出后获取变量 requestCount 的值

    function createRequest(string memory _fileHash) public {
        requestCount++;
        fileHash[requestCount] = _fileHash;
        emit RequestCreated(requestCount);
    }

我的问题是如何从 Node js 应用程序监听智能合约中发生的事件?

我使用的是 Web3 Version > 1,所以 watch 功能不适合我。

最佳答案

有一个 event.watch() 功能和一个关于如何使用它的很好的在线教程。 https://coursetro.com/posts/code/100/Solidity-Events-Tutorial---Using-Web3.js-to-Listen-for-Smart-Contract-Events

从教程中截取:

var instructorEvent = Coursetro.Instructor();
instructorEvent.watch(function(error, result){
            if (!error)
                {
                    $("#loader").hide();
                    $("#instructor").html(result.args.name + ' (' + result.args.age + ' years old)');
                } else {
                    $("#loader").hide();
                    console.log(error);
                }
        });

关于node.js - 如何从 node.js 应用程序永久监听智能合约中的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62342921/

相关文章:

javascript - 如何将 LiveReload 与 AngularJS 模板 URL 一起使用

javascript - 如何找出点击事件在哪里被捕获?

solidity - Metamask 未连接到本地主机 8545

javascript - 在 Protractor 测试中使用外部测试数据

javascript - javascript 中数组中值的匹配

ios - 如何检测键盘高度何时更新?

quicksort - Solidity 中的降序快速排序

ethereum - 插件错误 @nomiclabs/hardhat-etherscan : Error! 模块名称缺失或无效

javascript - Node - 如何将 MongoDB 时间戳转换为日期

javascript - 识别哪个 JS 脚本正在执行该事件