[Ethereum] Proper way of using allEvents()

eventslogsweb3js

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.

Best Answer

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);
});
Related Topic