0

您能解释一下为什么以下代码两次接收到相同的 trx 哈希吗?你有什么建议可以避免这种情况吗?

var Web3 = require('web3')
    const web3Subs = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws/v3/XXX'))
    const web3Trx = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws/v3/XXX'))
    const subscription = web3Subs.eth.subscribe('pendingTransactions')
    subscription.subscribe((error, txHash) => {
        if (error) console.log(error);
        console.log(txHash + " received.");
    })

输出 :

0x98219dad048aef55649d334a42c69ad094d3be1378f68b294aeaa2ef49ae2f97 received.
test.js:10
0x98219dad048aef55649d334a42c69ad094d3be1378f68b294aeaa2ef49ae2f97 received.
test.js:10
0x7f19d86f3c08c171060b0c29c0ad889dd7b2e69188ff6c8314caa4fb65e5b6a0 received.
test.js:10
0x7f19d86f3c08c171060b0c29c0ad889dd7b2e69188ff6c8314caa4fb65e5b6a0 received.
4

1 回答 1

0

看起来不像是 web3 问题,而是 RxJS 问题或您用来进行这些订阅调用的任何库……您订阅了两次,所以我想这就是您看到事情发生两次的原因。

const subscription = web3Subs.eth.subscribe('pendingTransactions'); // You subscribe here
subscription.subscribe((error, txHash) => {  // And you subscribe again to that subscription
        if (error) console.log(error);
        console.log(txHash + " received.");
    })

我想如果您以这种方式编写它可能会给您带来更好的结果,因为您不会订阅两次并且仍然将订阅分配给一个变量,以防您需要引用它:

const subscription = web3Subs.eth.subscribe((error, txHash) => {
        if (error) console.log(error);
        console.log(txHash + " received.");
    });
于 2020-01-23T20:15:03.983 回答