I have a smart contract with a custom token which holds some data. The Token data is defined in a struct and stored in an array:

struct Token {
    string text;
    uint256 value;

Token[] public _token;

On my web page I want to display all the tokens of the current user. Therefore I have a function in my smart contract which fetches all tokenIds of the given address. That function is really quick, but when I want to retrieve all Tokens from the Token[] array with the ids I get from the previous function it lasts very long! Especially if the user has many tokens...

To fetch all the tokens of the user I iterate over all tokenIds and perform the following request:

const token= await this.tokenContract.methods._token(tokenId).call();

Does anybody has an idea how to speed up the retrieval?


1 Answer 1


If you know the current number of tokens in your contract, then you can use Javascript's native asynchronous infrastructure:

const tokenIds = [...Array(numOfTokens).keys()];
const promises = tokenIds.map(tokenId => this.tokenContract.methods._token(tokenIds).call());
const tokens = await Promise.all(promises);

If you don't know the current number of tokens in your contract, then you can add in the contract a function which returns it:

function getNumOfTokens() public view returns (uint256) {
    return _token.length;

Your Answer

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

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