javascriptpromise.all

What is going on with this syntax? (let results = [], i;) I have never seen two values assigned to a variable


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?


Solution

  • 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);