I'm trying to build a very simple App using Web3 and JS. Basically the App should return the IDs of the tokens that a given user that is interacting with it holds in his wallet, and display the relative images. Here I'm interested in the first part. I don't think this is the most efficient way to do that (lot of calls), but still:
const getOwnerOf = (owner) => {
let ownedTokensArray = [];
for (let i = 1; i < 3333; i++) {
let ownerAddress = blockchain.smartContract.methods.ownerOf(i).call();
ownerAddress
.then(function(result){
console.log(result); // returns a wallet address (e.g 0x476e62b30E2587Ea937C19e2b60781e334fa29d7)
if (String(result) === String(owner)) {
ownedTokensArray.push(i);
}
})
}
console.log(ownedTokensArray); // should return an array of IDs but instead is []
}
Once I've collected all the IDs in the ownedTokensArray, I would like to make another function with more or less the same logic, where I iterate over the IDs array and make a fetch to an API using the IDs in order to display the image data connected to the correspondent tokens.
The problem is that ownedTokensArray is [] and while I've more or less guessed the concepts behind asynchronous calls I'm still facing difficulties.
Do I have to keep nesting the function by using .then()?
Is there a more convenient way (both syntax-wise and logically) to do this?
Why asynchronous calls are so difficult to understand thoroughly?
Thank you very much for your time.