0

Hello I'm trying to call the function "tryToGetData" using a recursive function inside a promise so it can pass me another different random value in order to keep trying to get a "success" response, at least, until the counter is set to 5 and if not just print 'Unable to load HTML'.

But the thing is that once I get the randomvalue it looks like no matter how many times I call the function to retrieve another random value it'll always be the same value as you can see below.

First, this is my code:

var a = ['unsuccessful', 'success'];
var randomValue = a[Math.floor(a.length * Math.random())];
let statuscounter= 0;

Promise.resolve(randomValue)

.then((value) => {
    console.log(value)
    return value
})
.then(function tryToGetData(status) {

  if (status !== "success" && statuscounter <= 5) {
      console.log('First attempt');

      statuscounter +=1
      return tryToGetData(randomValue)

  } else if(status !== "success" && statuscounter > 5){
      console.log('Unable to load HTML');
      return false;
  }else{
    console.log('HTML loaded, wait to load resources');
  }
})
.catch(error => reject(err));

This is the output if I get unsuccessful as the random value:

"unsuccessful"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"Unable to load HTML"

Whereas what I want is for example this:

"unsuccessful"
"First attempt"
//call the function again and in that case I'll get "success" as randomvalue:
"success"
"HTML loaded, wait to load resources"
Defoe
  • 371
  • 1
  • 5
  • 17
  • Please could you format your code so that the indentation levels are clear. – Oliver Charlesworth Mar 17 '17 at 11:11
  • 2
    _"no matter how many times I call the function to retrieve another random value"_ - You're never changing the value of `randomValue` O.o – Andreas Mar 17 '17 at 11:16
  • Edited. Ok @Andreas, how can I change it? It's suposed to be random, right? – Defoe Mar 17 '17 at 11:19
  • Get a new value from `a` before calling `tryToGetData(randomValue)` – Andreas Mar 17 '17 at 11:21
  • 1
    This `a[Math.floor(a.length * Math.random())];` doesn't give you a new random number every time you reference the variable it is assigned to – Callum Linington Mar 17 '17 at 11:22
  • Ok, Andreas, I see, now with tryToGetData(a[Math.floor(a.length * Math.random())]) works – Defoe Mar 17 '17 at 11:28
  • Would you have wondered the same if you had written `const randomValue = a[Math.floor(a.length * Math.random())];`? – Bergi Mar 17 '17 at 11:53
  • `.catch(error => reject(err))` looks like you are somehow using the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) – Bergi Mar 17 '17 at 11:54
  • yes, misspelled the error – Defoe Mar 17 '17 at 12:19

0 Answers0