javascript中的map()是否同步? [英] Is map() in javascript synchronous?

查看:197
本文介绍了javascript中的map()是否同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

功能是:

[1,2,3].map( function (item)
{
  console.log(item);
  //return 'something';
});

我的预期行为只有1作为输出,除非我取消注释

My expected behaviour is getting only 1 as output, unless i uncomment the

//return 'something'

但我真的得到了

1
2
3

我做错了什么?

更新:

我正在使用nodejs进行测试。

i am testing that with nodejs.

我真的不明白。

var async = require("async");

[1,2,3].map( function (item)
{
      console.log(item);
      //return 'something';
}); 
async.map([1,2,3], function (item,callback)
    {
        console.log(item);
        //callback(null,true)
    }, function (err,result)
        {
            console.log(result);
        }
);

两者都返回相同的

1
2
3

我真的我想等到我收到回复或回电,直到下一个项目被执行。

And i really would like to wait till i get a return or a callback till the next item is executed.

已解决

async.mapSeries([1,2,3], function (item,callback)
    {
        console.log(item);
        //callback(null,true)
    }, function (err,result)
        {
            console.log(result);
        }
);

是这样做的方式。

推荐答案

是的,地图是同步的。


这是一个更高阶的函数,它接受一个新函数并将其应用于给定的数组。

Yes, map is synchronous.
It's a higher order function, that takes a new function and applies it to the given array.

有些人认为因为他们将函数作为参数提供给 map 然后它'应该'就像一个事件回调函数,但它确实没有。 map 函数只是将函数参数应用于数组,并且只有在完成后,它才会在映射块之后继续执行生成的代码。

Some people think that because they give a function as a parameter to map then it 'should' act like an event callback function, but it really doesn't. The map function just applies the function parameter to the array and only after it finishes, it continues execution for the resulting code after the map block.

至于你的预期行为 - 它就像你想象的那样不起作用;)

As to your 'expected behavior' - it just doesn't work like you think ;)

这篇关于javascript中的map()是否同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆