Promise.all() in Cloud Function

I am trying to retreive all NFTs of a give contract. I call the Web3 API v2 inside a Cloud Function.

Moralis.Cloud.define("getAll", async (request) => {
    let url = 'https://deep-index.moralis.io/api/v2/nft/'+request.params.address;
    return Moralis.Cloud.httpRequest({
        url: url,
        params: { chain: request.params.chain, chain_name: "mainnet" },
        headers: {
            'accept': 'application/json',
            'X-API-Key': 'xyz'
        }
    }).then(function (httpResponse) {
        return httpResponse.data;
    }, function (httpResponse) {
        logger.info("error");
        logger.info(httpResponse);
    })
});

This works. I get a results array with 500 results. The total number of all results however would be 3498, which the httpResponse.total tells me.

Since there is a hardcap of limit of 1000 I need to calculate how many httpRequests I need to do in order to retreive all 3500 items, mainly like 3500 / 500.

So I would need to make 7 httpRequest. How would I do that as a Promise.all() version within the Cloud Function. I do not get it to work.I tried this approach(no calculation yet), but not working:

Moralis.Cloud.define("getAll", async (request) => {
    let url = 'https://deep-index.moralis.io/api/v2/nft/'+request.params.address;
    let httpResponse = Moralis.Cloud.httpRequest({
        url: url,
        params: { chain: request.params.chain, chain_name: "mainnet" },
        headers: {
            'accept': 'application/json',
            'X-API-Key': 'xyz'
        }
    }).then(function (httpResponse) {
        return httpResponse.data;
    }, function (httpResponse) {
        logger.info("error");
        logger.info(httpResponse);
    })

    const retrieveAll = async function() {
        let results = await Promise.all([httpResponse]);
        logger.info(results);
    };

    return retrieveAll;
});

Any suggestions appreciated.

1 Like

Hey @ArgonVogel

I’ve prepaired the hardcoded example with historical balances:

Moralis.Cloud.define("getBlocks", async (request) => {
  const toBlocks = ["10165828", "10135828", "10125828", "10115828"];
  const requests = toBlocks.map((toBlock) => {
    return Moralis.Cloud.httpRequest({
      url: `https://deep-index.moralis.io/api/v2/xxxxxxxxxxx/erc20?chain=bsc&to_block=${toBlock}`,
      headers: {
        accept: "application/json",
        "X-API-Key": "xxxxxxx",
      },
    });
  });
  return await Promise.all(requests);
});

Hoep this will help you :man_mechanic:

3 Likes

That actually helped quite a lot @Yomoo
I am coder, but new to javascript so the map function was new to me. Works now.

2 Likes