1

I'm a total n00b to Promises, and would like to use them more, but need a little help. Take the code example below:

for (var key in list){
    DoSomething(list[key])
        .then(function(){
            console.log(key);
        });
}

function DoSomething(item){
    return new Promise(function(resolve, reject){
        resolve();
    });
}

The console.log(key) part wont work correctly because the variable key is modified in the outer scope. A way to fix that might be to resolve the promise with the key value but unfortunately, the DoSomething method is part of a shared library.

for (var key in list){
    DoSomething(list[key], key)
        .then(function(key){
            console.log(key);
        });
}

function DoSomething(item, key){
    return new Promise(function(resolve, reject){
        resolve(key);
    });
}

Is there any other way to get the for loop console.log(key) to work correctly?

Jimbo
  • 21,476
  • 39
  • 113
  • 157

2 Answers2

2

Use let instead of var and it would work

let list = {a:1, b:2};

for (let key in list){
    DoSomething(list[key])
        .then(function(){
            console.log(key);
        });
}

function DoSomething(item){
    return new Promise(function(resolve, reject){
        resolve();
    });
}
marvel308
  • 9,972
  • 1
  • 18
  • 31
1

Use IIFE

for (var key in list){
    (function(key){
        DoSomething(list[key])
        .then(function(){
            console.log(key);
        });
     })(key);
}
Nikhil Aggarwal
  • 27,657
  • 4
  • 40
  • 56