是Node.js Array.map()异步吗? [英] Is Node.js Array.map() asynchronous?

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

问题描述

我可以指望nodeIDs映射在每次调用doSomething()时完成吗?

Can I count on nodeIDs mapping is completed every time doSomething() is called?

nodeIDs = $.map(nodeIDs, function(n){
    return n.match(/\d+$/);
});
doSomething(nodeIDs);

我认为node.js中的所有回调都是异步的我读过一篇关于一般编程的文章,回调可以是同步的,但我不知道node.js?

I thought all callbacks in node.js are asynchronous? I did read an article on general programming that callback could be synchronous but I am not sure about node.js?

推荐答案

JavaScript也是一种函数式编程语言。你在这里有一个高阶函数,一个函数作为参数。高级函数是同步的(但参见下面的注释)。

JavaScript is also a functional programming language. What you have here is a «higher order function», a function which takes a function as a parameter. Higher order functions are synchronous (but see note below).

资料来源:

  • Functional Programming
  • Higher order functions in JavaScript

map()功能。它接受一个函数并将其应用于数组的所有元素。定义听起来很功能»。 Node也不提供此功能。它由 MDN Array.prototype.map(),并由 ECMAScript 5.1 指定。

map() is a typical example of a higher order function. It takes a function and applies it to all elements of an array. The definition sounds very «functional». This function is also not provided by Node. It is documented by MDN Array.prototype.map() and specified by ECMAScript 5.1.

要回答你的问题:是, doSomething(nodeIDs)在之后调用。

To answer your question: Yes, doSomething(nodeIDs) is called after all elements have been applied.



注意:高阶函数是函数式编程的概念。 JavaScript是功能的,但也深深地落实在浏览器或服务器上执行代码的实用性。我会说,例如 setTimeout()不是一个更高阶的函数,即使它需要一个函数作为参数,因为 setTimeout()不是真正纯粹的功能,因为它使用时间。纯功能是永恒的。例如, map()的结果不依赖于时间。这就是这个问题是真的。如果某事不依赖于时间,则同步执行它。问题解决。


Note: The higher order function is a concept of functional programming. JavaScript is functional, but also deeply seated in the practicality of executing code inside a browser or on the server. I would say that for example setTimeout() is not a higher order function even if it takes a function as a parameter because setTimeout() is not really purely functional because it uses time. Pure functionality is timeless. For example the result of map() doesn't depend on time. And that's what this question is really about. If something doesn't depend on time you execute it synchronously. Problem solved.

感谢Simon挑战JavaScript中高阶函数的定义。

Thanks to Simon for challenging the definition of the higher order function in JavaScript.

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

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