0

I have a Javascript/Typescript code that looks like this:

for (let item of itemList) {
  this.myService.myMethodReturningPromise(item.id).then(success => {
    item.value = success;
  });
}

By the time my Promise resolves, I have already exited the loop and I no longer have reference to item.

Why is it able to correctly set the value of each item in itemList?

franco
  • 667
  • 4
  • 7
  • 20
  • 2
    Ordinary scoping rules. Even if the main thread has ended, the function is still a *closure* and can see the `item`. – CertainPerformance Jun 22 '18 at 00:03
  • @CertainPerformance is right, in other words, you can get access to `item` only inside this `for` loop (if you will not additionally store the value outside the loop). – P.S. Jun 22 '18 at 00:06
  • @CertainPerformance `main thread has ended,` you didn't really mean to say that did you?. :) – Keith Jun 22 '18 at 00:08
  • Thanks. Closures are really confusing but at least now I know what that happens. – franco Jun 22 '18 at 00:12
  • @Keith I *think* that's the proper way to say it - the main thread runs, finishes, then asynchronous Promises and setTimeouts and such have a chance to resolve. Might it be phrased differently? – CertainPerformance Jun 22 '18 at 00:14
  • 1
    @CertainPerformance There is only ever 1 thread in JS, the main thread. I think you could just say the loop has finished. It's not a big deal :), with all the new Async stuff with JS, it's easy to forget it's not threaded. And at its core works similar to a cooperative multi-tasking OS. – Keith Jun 22 '18 at 00:25

0 Answers0