0

I'm beginner and I think the answer is easy, but after searching I'm not able find the answer.

I try to log "tab" but it seem tab += player.name don't affect my var tab = "";

tab = "";
for (var id in response.items) {
        clash({request: {proxy: process.env.PROXIMO_URL}}).playerByTag(response.items[id].tag).then(player => {
        tab += player.name;
    })
}

console.log(tab);

Thank you for your help.

ssilas777
  • 9,672
  • 4
  • 45
  • 68
Antoine
  • 3
  • 1
  • 2
    Welcome to the wonderful world of aynchronous execution. Try to log `tab` right after you add the player name to it, and see the difference. – Robby Cornelissen Mar 28 '18 at 04:04
  • `console.log()` prints `tab` way before the function executes. – Mamun Mar 28 '18 at 04:06
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Sebastian Simon Mar 28 '18 at 04:20

1 Answers1

0

playerByTag is running asynchronously, so you can't get the responses synchronously as you're doing now. If you're OK waiting in serial, just put it inside an async function and use await:

(async () => {
  let tab = "";
  for (let item of response.items) {
    const player = await clash({request: {proxy: process.env.PROXIMO_URL}})
      .playerByTag(item.tag);
    tab += player.name;
  }
  console.log(tab);
})();

If you want to run the requests in parallel, you'll have to use Promise.all.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320