-1

I have the code in native JavaScript (I simplified it):

var finalArray = [];

for (var i; i < 3; i++) {
    var a = -1;  // set the default value
    var b = Math.random();

    ymaps.route(someArray[i]).then(function (res) {
        a = res.getCoordinates();     
    });

    finalArray.push([a, b]);
}

console.log(finalArray);

There is some third-party framework called ymaps which has a method route which returns a promise object. Problem cases in that I need to wait until promise.then callback function is done, then continue the main code with function finalArray.push([a, b]);, or, rather, synchronize asyncronous processes.

Result of code I wrote above is

[
    [-1, /*random*/],
    [-1, /*random*/],
    [-1, /*random*/]
]

But instead of -1 - the default var a value, some plural number (changed var a in promise.then callback function) must be there.

dgvid
  • 26,293
  • 5
  • 40
  • 57
impulsgraw
  • 887
  • 3
  • 13
  • 34
  • Please add the code for the callback function you pass to `.then()`. There is no way to answer your question without seeing it. – dgvid Apr 23 '15 at 16:40
  • Look up better, here it is `function(res){ a = res.getCoordinates(); }` – impulsgraw Apr 23 '15 at 20:43

1 Answers1

3

You cannot just "continue with the main code". Promises are asynchronous, and your callback (that assigns a) will be executed only after you have tried to use a in finalArray.push([a, b]);. See Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference.

Instead, you will need to put your main code in a callback as well. You can get another promise for the results of all three loop-generated promises, see Pass in an array of Deferreds to $.when().

function makePromise(a, b) {
    // scope necessary for closure
    return ymaps.route(someArray[i]).then(function(res) {
        a = res.getCoordinates();
        return [a, b];
    });
}

var promises = [];
for (var i; i < 3; i++)
    promises.push(makePromise(-1, Math.random()));
$.when.apply($, promises).then(function() {
    var finalArray = Array.prototype.slice.call(arguments);
    console.log(finalArray);
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375