0

I found this example of how to implement a Promise.all method.

function all(iterable){ // take an iterable 
  // `all` returns a promise.  
  return new Promise(function(resolve, reject){ 
    let counter = 0; // start with 0 things to wait for
    let results = [], i;
    for(let p of iterable){
        let current = i;
        counter++; // increase the counter 
        Promise.resolve(p).then(function(res){ // treat p as a promise, when it is ready: 
          results[i] = res; // keep the current result
          if(counter === 0) resolve(results) // we're done
        }, reject); // we reject on ANY error
       i++; // progress counter for results array
    }
  });
}

I am not sure what is going on with this line of code: let results = [], i;

When I run that in the console i becomes undefined. In the all function they are doing i++, but using that operator on undefined value becomes NaN. What is going on here? If 'i' is undefined, how are they able to use it as an index on an array for results[i] = res; // keep the current result?

jhaubrich.com
  • 79
  • 2
  • 10
  • It's effectively: `let results = []; let i;` (and hence `i` is implicitly undefined). – jarmod Oct 13 '21 at 16:13
  • but if `i` is undefined, why is the author then trying to use the ++ operator on it? Do you think the author made a mistake? – jhaubrich.com Oct 13 '21 at 16:15
  • 1
    Yes, it's a bug. Inappropriate use of uninitialized variable. It won't generate a runtime error, however, because (foolishly) JavaScript allows `results[NaN]`. – jarmod Oct 13 '21 at 16:17
  • 1
    The code is actually very poor. It will never, for example, resolve a value (because, as far as I can see, counter never has the value zero at the point the code decides to resolve results) and so it doesn't expose the (bad) results externally. – jarmod Oct 13 '21 at 16:24

2 Answers2

2
let results = [], i;

is equivalent to

let results = [];
let i;
kopz
  • 738
  • 11
  • 20
1
let results = [], i;

is same as:

let results = [];
let i;

i gets the value undefined. Any math on undefined will return NaN not a number.

console.log(undefined + 1);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39