Search code examples
node.jsexpressethereumcallweb3js

Nodejs Express: Getting different output in console.log and callback


I have a smart contract deployed on Kovan, which contains a getter function:

function getOrderStatus(uint _orderId) public view returns(bool shipped, bool arrived, bool payed) {
    return (orders[_orderId].shipped, orders[_orderId].arrived, orders[_orderId].payed); 
}

If I call the function via web3 I get the following output on the console, which is fine!:

Result {
  '0': false,
  '1': false,
  '2': false,
  shipped: false,
  arrived: false,
  payed: false }

But if I try to forward the returned object via a callback function to provide it e.g. via an API, I get the following output on my Browser:

[object Object]

The only difference is instead of console.log(returnValue) --> callback(returnValue) at the end of the following code:

function getOrderStatus(_orderId, callback) {
    contractABI.methods.getOrderStatus(_orderId).call()
        .then(returnValue => callback(returnValue));
}

The function is then being called via Express

app.get('/api/getOrderStatus', function(req, res) {    
    orderId = req.query.orderId;        
    getOrderStatus(orderId, function(error, data) {
        if (!error) {
            res.send(data);
        }
        else 
        {
            res.send(error);    
        }
    });    
});

Solution

  • If your getOrderStatus() function is like this:

    function getOrderStatus(_orderId, callback) {
        contractABI.methods.getOrderStatus(_orderId).call()
            .then(returnValue => callback(returnValue));
    }
    

    ... then your result is in returnValue, right? If you then call your callback function like described above, then the first parameter is your data.

    In your route, you are calling the callback with the error parameter at first parameter, so I guess it should be this way:

    app.get('/api/getOrderStatus', function(req, res) {    
        orderId = req.query.orderId;        
        getOrderStatus(orderId, function(data, error) {  // <--- changed order of parameters
            if (!error) {
                res.json(data);
            } else {
                res.send(error);    
            }
        });    
    });
    

    Hope that helps ...