1

I was looking at where i needed to go in my coding, and see i need a pattern to handle the 'many' calls. for example a call only returns 1 set of data, when i need perhaps records 1-70.

Is the following snippet a 'good'/'bad'/'ugly' way of handling this, and if not 'good' what is a better way?

return countvariablecall()
.then((results) => {
    for(let i=0; i< results.c[0]; i++){
        return manyTimesCalledFunction(i).
        then ((result) => {
            do something with the result.
        )}
    }
})
  • 1
    Nothing wrong with that but just make sure you use like a redux store and pagination when you can. You might want to look into thegraph.com as well. – Nico Vergauwen Aug 27 '18 at 22:30
2

I think what you are trying to do here is resolve a bunch of promises, in which case, I would normally create an array of promises, and resolve them all with Promise.all().

Something like this:

// This is just an example of a function that returns a promise
function delayedNum (num) {
      return new Promise(resolve => {
    setTimeout(() => {
      resolve(num);
    }, 2000);
  });
}

function main() {
    // create an array for your promises
    promises = []

    // queue and push your promises to the array
    for(i = 0; i < 20; i++) {
    // Note you can queue .then() statements too
        promises.push(delayedNum(i)
        .then(function(result) {
            return result * 2;
        }));
   }

  // resolve all promises and play with the results
  Promise.all(promises).then(function(result) {
    console.log(result)
  });
}

console.log(result) will be an array of the numbers 0-38, counting by 2's, in order, which you can manipulate easily.

  • THIS i like! thank you. while i expected the other way to 'work', it felt a little 'shod' together. – shaddow Aug 27 '18 at 22:55
  • No prob. If it helps, you can also check out where I actually used this pattern to show UX based on a solidity view function here. – Shawn Tabrizi Aug 27 '18 at 22:59
  • actually it's very much like my migration file with the promises.all. Thank you for pointing it out so i 'got it'. As soon as i saw what you wrote, it was exactly what i was looking for, appreciate. – shaddow Aug 27 '18 at 23:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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