I'm trying to create a web api function with NodeJS and Express, retrieving data from private ethereum blockchain.
The problem is that the method mytoken.tokenOfOwnerByIndex...
is async method in loop but want to wait all results until done and let the function returns tokenIds as a result.
I tried to use async/await but don't know how to use them properly.
Here is the snippet of my current code:
app.get("/get", function(req, res, next){
var Web3 = require('web3');
var BigNumber = require('bignumber.js');
Web3.providers.HttpProvider.prototype.sendAsync = Web3.providers.HttpProvider.prototype.send;
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var contract = require("truffle-contract");
var contractJson = require("./build/contracts/MyToken.json");
var MyToken = contract(contractJson);
MyToken.setProvider(web3.currentProvider);
var tokenIds = [];
MyToken.deployed().then(function(mytoken) {
var account0 = web3.eth.accounts[0];
mytoken.balanceOf(accounts0).then(function(balance){
var x = balance.toNumber();
for (i = 0; i < x; i++){
mytoken.tokenOfOwnerByIndex(account0,0).then(function(tokenId){
var y = tokenId.toNumber();
tokenIds.push(y);
});
}
res.json(tokenIds);
});
});
});
Can anyone guide me or give me the clue?