3

I have .js file, where the contract has to call five times by passing rand as parameter. But rand has been overwritten and only the fifth random value is passed to the contract five times:

for(var i=0;i<5;i++){
    var rand =Math.random();
    contractt.deployed().then(function(instance){
    var instancee =instance;
         return instancee.add(rand,{from:wallet,gas:4000000});
        }).then(function(result) {
            console.log('result='+result);
        }) 
   })
} 

I tried using setTimeout() as below:

 for(var i=0;i<5;i++){
    setTimeout(()=>{
    var rand =Math.random();
    contractt.deployed().then(function(instance){
    var instancee =instance;
         return instancee.add(rand,{from:wallet,gas:4000000});
        }).then(function(result) {
            console.log('result='+result);
        }) 
   })
  },1000);
} 

However, I still obtain the same result.

4

This is not really an Ethereum question..

See https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example

For your concrete case, you could do this:

for(var i=0;i<5;i++){
    contractt.deployed().then(function(instance){
        var instancee = instance;
        return instancee.add(Math.random(), {from:wallet,gas:4000000});
    }).then(function(result) {
        console.log('result='+result);
    })
} 

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