我的map函数总是先运行吗?

Will my map function always run first

本文关键字:运行 map 函数 我的      更新时间:2023-09-26

map函数是否总是在if语句运行之前完成运行?我想确保数组中的元素总是在if语句运行之前被加起来。是否会有这样一种情况,map函数在if语句开始之前没有完成运行,因此if语句将无法获得add变量的真实值?

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!!")
}

是。除非你有异步请求或者像WebWorkers这样的多线程操作,否则你的代码是同步的,也就是说它是按照严格的顺序执行的。

Array.prototype.map of javascript is synchronous,但如果您想要async行为,您可以使用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