0

Given the below code:

var arr = ['one', 'two']

for (index in arr) {
  console.log('outside promise:', arr[index])

  myPromise().then(function(response) {
    console.log('inside promise:', arr[index])
  })
}

My output:

// outside promise: one
// outside promise: two
// inside promise: one
// inside promise: one

Why the hack the console output inside the promise doesn't loop trough values?

  • 1
    Could you be more clear, I don't really understand what your stating the issue is? – Spencer Wieczorek May 25 '17 at 22:25
  • Where is `myPromise` defined? What is expected result? – guest271314 May 25 '17 at 22:27
  • inside your loop try var x = arr[index]; then console.log(x) inside the promise – PenAndPapers May 25 '17 at 22:29
  • Check this answer https://stackoverflow.com/questions/43130019/how-to-chain-promises-in-for-loop-in-vanilla-javascript – D-Marc May 25 '17 at 22:31
  • 4
    I'm surprised at your claimed output - it **should** output `inside promise: two` twice not `inside promise: one` twice - the issue is to do with asynchronicity - by the time BOTH `.then`s get called, index is 1 - therefore arr[1] will be logged – Jaromanda X May 25 '17 at 23:01
  • 1
    @PenAndPapers - that would make zero difference – Jaromanda X May 25 '17 at 23:03
  • [Don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572) And [don't forget to declare your `var`iables!](https://stackoverflow.com/q/1470488/1048572) – Bergi May 25 '17 at 23:31

1 Answers1

0

As @Jaromanda X stated in the comment, correct output will be:

// outside promise: one
// outside promise: two
// inside promise: TWO
// inside promise: TWO

Since promises will be resolved when index already will be 1, not 0. If you getting different results in console, it can be stdout concurrency issues. Try to add results to the array, and then output it;

const arr = ['one', 'two'];
let results = [];

for (index in arr) {
  results.push(`outside promise: ${arr[index]}`)

  myPromise().then(function(response) {
      results.push(`inside promise: ${arr[index]}`)
  })
}

console.dir(results);
Sergey Yarotskiy
  • 4,536
  • 2
  • 19
  • 27
  • There is no difference wether you log the value or push it to an Array (in terms of timing). The problem is the same. – Thomas May 25 '17 at 23:30
  • @Thomas which problem? – Sergey Yarotskiy May 25 '17 at 23:31
  • that the `array[index]` inside the closure will be resolved AFTER the loop has FINISHED iterating. And that for all iterations with the same index, the last one. – Thomas May 25 '17 at 23:33
  • It is not a problem. It is expected behavior. Problem is, that user demonstrates unexpected behavior - his output from promise `one, one`, not `two, two` – Sergey Yarotskiy May 25 '17 at 23:35