1

I want to get event log to do other thing, so I try to use for loop to get the event log in the websjs.

I try to use async and await, but order is wrong.

Here is my web3js sample code

    handleContractHistory: async function(event){
        var log_info = {};
        var abi = App.contracts.Crowdsale.abi;
        var ClientReceipt = web3.eth.contract(abi);
        var clientReceipt = ClientReceipt.at(my_contract_address);
        var event = clientReceipt.PurchaseLogs({}, {fromBlock: 0, toBlock: 'latest'});

        await event.get(function(error, logs){

          for(var index = 0; index < logs.length; index ++){
            log_info[logs[index].blockHash] = 1;
            console.log(logs[index].blockHash);
          }

        });

        console.log(log_info);
    }

Here is the result of console

{}
0x6b6c29cd8c693205d41*****************
0x6b628cd04b093b731e1*****************
0x6b6c29cd8c645eb54f2*****************

Does that have other way that can let function to wait to get the data in the loop?

1 Answer 1

0

You can create a promise function and use await for waiting until all events are collected, just like below code.

Promise function:

const WaitAllContractEventGet = function(myevent) {
    return new Promise(function(resolve, reject) {
        myevent.get(function(error, logs) {
            if (error !== null) {
                reject(error);
            }
            var log_info = {};
            for (var index = 0; index < logs.length; index++) {
                log_info[logs[index].blockHash] = 1;
                console.log(logs[index].blockHash);
            }                                                                                                                   
            resolve(log_info);
        });
    });
};

Callee:

handleContractHistory: async function(event){
    var log_info = {};
    var abi = App.contracts.Crowdsale.abi;
    var ClientReceipt = web3.eth.contract(abi);
    var clientReceipt = ClientReceipt.at(my_contract_address);
    var event = clientReceipt.PurchaseLogs({}, {fromBlock: 0, toBlock: 'latest'});
    const log_info = await WaitAllContractEventGet(event);
    console.log(log_info);
}
0

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.