Web3.js NodeJS – How to Make NodeJS Wait Until a Promise Resolves Inside a Subscription

javascriptnodejsweb3js

I have the following code:

import Web3 from 'web3';

function waitForFunds() {
    let web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
    return new Promise((resolve, reject) => {
        web3.eth.subscribe('pendingTransactions').on("data", resolve);
    });
};

(async function () {
    await waitForFunds();
    console.log('Waiting');
})();

I would expect that nodeJS waits until the promise returned by waitForFunds() gets resolved, but instead, NodeJS is just exiting immediately and not waiting for the subscription to resolve the promise upon receiving data. The console never logs "Waiting". Am I doing anything wrong?

Best Answer

In order to subscribe to events, you need a Websocket endpoint. This is your code updated to use WSS:

var Web3 = require('web3')

async function waitForFunds() {
  let web3 = new Web3(
    new Web3.providers.WebsocketProvider(
      'wss://your-websocket-endpoint/12345'
    )
  )
  return new Promise((resolve, reject) => {
    web3.eth.subscribe('pendingTransactions').on('data', resolve)
  })
}

waitForFunds()
console.log('Waiting')

Also, if you want to list pending transactions, you can use something like this:

var Web3 = require('web3')

const main = async () => {
  var web3 = new Web3(
    new Web3.providers.WebsocketProvider(
      'wss://your-websocket-endpoint/12345'
    )
  )

  var subscription = web3.eth
    .subscribe('pendingTransactions', async (error, result) => {
      if (error) console.log('error', error)
    })
    .on('data', async (transaction) => {
      console.log('TRX >>', transaction)
      const trxDetails = await web3.eth.getTransaction(transaction)
      console.log('trxDetails', trxDetails)
    })

}

main()

You can use Chainstack to get HTTP and WSS endpoints to multiple blockchain protocols.

Related Topic