0

I'm facing async call problem in javascript with wrong (not the expected) value being passed to the function. See pseudocode:

    i=0;
    while(i<10){  
        var obj= {something, i};    
        getcontent(obj); //( <--- getcontent is async function/problem)      
     i++;
    }

All getcontent async calls use the last i = 9 value, which is not what i want to achieve.
How do/should i process such async calls and get correct/pass correct i values in every call??

Saulius S
  • 391
  • 2
  • 4
  • 12

3 Answers3

0

<script>
var i = 0;
while (i < 5) {
setTimeout(function() { 
 getcontent()
}, 2000);  
    i++;
}
function getcontent(){
alert()
}
</script>

Hope it will help you

Rahul Mahadik
  • 11,668
  • 6
  • 41
  • 54
0

How about this:

async function loop(){
    var i: number = 0;
    while (i < 10) {
        (async function () {
            var obj = { "@": "fd", "#": i };
            await getcontent(obj); //( <--- getcontent is async function/problem)      
            i++;
        })();
    }
}
0

I think this is what you are looking for~~

var funcs = [];
var i = 0;
while (i < 10) {
  funcs[i] = (function(index) {
    return function() {
      var obj = { '@': 'fd', 'index': index};
      return getcontent(obj); //( <--- getcontent is async function/problem)
    };
  }(i));
  i++;
}

function getcontent(obj) {
  console.log("My value: " + obj.index);
};

funcs.forEach(function (item) { item(); });
Teocci
  • 7,189
  • 1
  • 50
  • 48