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

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

问题描述

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

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).

来源:

map() 是高阶函数的典型例子.它接受一个函数并将其应用于数组的所有元素.这个定义听起来很功能性".Node.js 也没有提供这个功能.它记录在 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天全站免登陆