0

Will the map function always finish running before the if statement runs? I want to make sure that the elements in the array are always added up before the if statement runs. Will there ever be a time when the map function doesn't finish running before the if statement starts and so the if statement will not get the true value of the add variable?

var arr = [ '33.3%', '33.3%', '33.3%' ];
var add = 0;

arr.map(function(elem){
    add += parseInt(parseFloat(elem)*10000)
});

if (add <= 1001000 && add >= 999000) {
    console.log("passed!!")
}
Ruth
  • 614
  • 2
  • 6
  • 20
  • 2
    Yes, the map function will always finish first, as javascript is single threaded, and all your code is synchronous – adeneo Oct 14 '16 at 11:26
  • Tip: If it's a *synchronous* callback, it will **always** finish first. If it's an *asynchronous* callback, it will **always** finish later. It's not a race, there's logic to it. – deceze Oct 14 '16 at 12:09

2 Answers2

0

Yes. Unless you have asynchronous requests or multi-threaded operations like WebWorkers, your code is synchronous, i.e. it is executed in strict order.

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

Array.prototype.map of javascript is synchronous, but if you want an async behaviour you can use nodejs async module.

NodeJS Async Map

var async = require('async');

var arr = ['1','2'];
async.map(arr, getInfo, function (e, r) {
  console.log(r);
});

function getInfo(name, callback) {
  setTimeout(function() {
    callback(null, name + 'new');
  }, 1000);
}

http://code.runnable.com/UyR-6c2DZZ4SmfSh/async-map-example-for-node-js

Thalaivar
  • 23,282
  • 5
  • 60
  • 71