0

I implemented a function which sums values from an array by using promises. The algorithm generates work and pushes that to the task list. After, the promises are processed at the same time.

function test(){
    var arr = [10,20,30];
    for(i=0; i<arr.length; i++){
        var value = arr[i];
        var tasks = [];
        var work = (
            sumValues(value).then((res) => {
                return ({"value": value, "sum":res});
            })
        );
        tasks.push(work);
    }

    return Promise.all(tasks).then(function (sum_arr) {
        console.log(sum_arr);
    }).catch(function (e) {
        return false;
    });
}


function sumValues(v){
    var promise = new Promise(function (resolve, reject) {
        try {
            resolve(
                v + 100
            );
        } catch (err) {
            reject(Error(err));
        }

    });
    return promise;
}


test();

But there is a problem, the returned value is always the last value of the array. I suspect that when the cycle iterator changes, it changes the position in the pre-processed promises and then returns the last value of the array.

The correct return should be an array of three elements, not one. What is the best approach to fix this problem?

  • 1
    Try the advice outlined in the answers to [this question](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – Heretic Monkey Apr 17 '17 at 15:22
  • @MikeMcCaughan, the problem was a scope problem so I just created a wrap function and it worked. Thanks. – André Lizardo Apr 17 '17 at 18:57

0 Answers0