0

I'm trying to get all events for a contract:

let events = token.allEvents({fromBlock: creationBlock, toBlock: 'latest'}, (err, res) => {
    try {
        let result = events.get();
        console.log(result);            
    } catch (error) {
        console.error(error);            
    }
});

For some reason, the callback code is called every time an event is found. I could live with that, but if there are no events, the callback is never called. I'm trying to list all events for a contract (not interested in watching for events).

When I try to use it synchronously, events.get() throws an error saying synchronous methods are not supported.

2
  • 1
    "For some reason, the callback code is called every time an event is found." That's the expected behavior. I'm a bit confused about what you're trying to do. Could you explain? Maybe give an example?
    – user19510
    Jul 31, 2018 at 13:50
  • @smarx I need to get all events emitted by my contract.
    – ulu
    Jul 31, 2018 at 14:50

1 Answer 1

0

Turned out I shouldn't have used the callback in this case. Here's the working code:

let events = token.allEvents({fromBlock: creationBlock, toBlock: 'latest'});
events.get((error, events) => {
    if (error)
        console.log('Error getting events: ' + error);
    else
        return res.json(events);
});
4
  • I believe this is just a longer way of writing the code that uses a callback. (The callback already gets invoked for each event that occurs. I think the issue is that you were then calling get again instead of just logging the event.)
    – user19510
    Jul 31, 2018 at 14:59
  • I'm writing a backend handler that needs to return all past events to the client. So, waiting until an event happens is not an option for me. Using a callback for allEvents would be handy for a frontend code that displays events in real time.
    – ulu
    Aug 1, 2018 at 11:00
  • 2
    Oh, sorry, just realized you're doing get instead of watch. The callback supplied to allEvents is equivalent to watch.
    – user19510
    Aug 1, 2018 at 11:42
  • OK, good to know. I couldn't find anything in the docs explaining this.
    – ulu
    Aug 1, 2018 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.