异步与异步的NodeJS调用响应 [英] Async calls with async response in NodeJS

查看:184
本文介绍了异步与异步的NodeJS调用响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建设我的第一个项目,在这些日子里的NodeJS但我是一个有点困惑上的任务,我相信这是一个简单的,我想这个问题是我缺少这些异步方法的知识,但我找不到回答任何地方。

I'm building my first project with NodeJS in these days but I'm a bit confused on a task I believe it's a simple one, I guess the problem is my lack of knowledge of these async approach but I cannot find the answer anywhere.

我有一个简单的循环迭代数组和任何元素,基于某些规则,我会打电话给一个函数或其他。
现在,有些操作会比别人快,所以我可以与N元素返回早于上元素N-1的功能的功能告终。
为简单起见,像这样

I've a simple loop iterating over an array and for any element, based on some rule, I'll call a function or another. Now some operation will be faster than others so I could end up with a function on element N returning sooner than the function on element N-1. To make it simple something like this

for (var i = 0 ; i < 10 ; i++) {
      if (i%2 === 0) {
          setTimeout(function(i) {
               console.log(i);
          }, 2000);
      }
      else { console.log(i); }
}

所以任何偶数将印有2秒滞后而奇号码将被立即打印。
反正运行它,我得到

so any even number will be printed with 2 seconds lag while the odd numbers will be printed immediately. Anyway running it I get

1
3
5
7
9

<<2 seconds break>>

undefined
undefined
undefined
undefined
undefined

看起来甚至值丢失。
如何传递,确保功能不会丢失输入值的价值?
我缺少的东西吗?

looks like the even value is "lost". How can I pass the value making sure the function won't lose the input value? Am I missing something?

谢谢,
毛罗

推荐答案

的setTimeout 参数函数声明为一个参数, I 。当的setTimeout 调用不带参数的功能,因为它的参数,因此设置为未定义

Your setTimeout argument function is declared to take a single parameter, i. When setTimeout calls the function with no arguments, as it does, the parameter is thus set to undefined.

这似乎是要稍好一些,因为它不再阴影外您最初试图引用我变量...

This would seem to be be slightly better, as it no longer shadows the outer i variable you were originally trying to reference...

setTimeout(function() {
  console.log(i);
}, 2000)

...但如果​​你运行它,你会发现它打印 10 5次,因为每次你创建函数引用相同的变量,其值将是 10 时,循环退出条件变为真正,它终止。

...but if you run it, you'll find it prints 10 5 times, because every function you create is referencing the same i variable, whose value will be 10 when the loop exit condition becomes true and it terminates.

创建的闭合的持有 i的值,因为它是在循环过程中,每个 setTimout 参数函数创建将这样的伎俩:

Creating a closure which holds the value of i as it was during the loop in which each setTimout argument function was created will do the trick:

setTimeout((function(i) {
  return function() {
    console.log(i);
  }
})(i), 2000)

重命名的参数,<一个href=\"http://benalman.com/news/2010/11/immediately-invoked-function-ex$p$pssion/\">Immediately-Invoked功能防爆pression 我们只是使用可能有助于更清楚:

Renaming the argument to the Immediately-Invoked Function Expression we just used might help make things clearer:

setTimeout((function(loopIndex) {
  return function() {
    console.log(loopIndex);
  }
})(i), 2000)

我们是:


  • 创建一个函数,它接受一个参数,并返回另一个函数。

  • 立即的呼唤外的功能,它传递的电流值i (这是不是对象,因此有效地传递值)。

  • 外部函数返回内部的功能,这是作为参数传递给的setTimeout

  • Creating a function which takes a single argument and returns another function.
  • Immediately calling the "outer" function, passing it the current value of i (which is not an object, so is effectively passed by value).
  • The "outer" function returns the "inner" function, which is passed as the argument to setTimeout.

这工作,因为:


  1. 创建一个JavaScript函数创建一个新的范围的持有函数的参数变量,并使用 VAR其中声明任何其他变量关键字。想到这像对应的变量名称属性的不可见的对象。

  1. Creating a function in JavaScript creates a new scope to hold the function's argument variables and any other variables declared within it using the var keyword. Think of this like an invisible object with properties corresponding to the variable names.

所有功能都抱到它们被定义的范围,参考作为其一部分的作用域链的。他们仍然可以访问此范围内,即使它不再是积极的(例如,当它的功能是为回报创建)。 内部函数,其中包含一个 loopIndex 变量范围内创建,设置为 i的值在时间IIFE被调用。所以,当你尝试引用一个名为变量 loopIndex 从内部函数内部,它首先检查自己的范围(以及没有找到 loopIndex 有)的然后的开始走了它的作用域链 - 首先,它会检查它被定义的范围,其中的的包含 loopIndex 变量,它的值传递给的console.log()

All functions hold a reference to the scope in which they were defined, as part of their scope chain. They still have access to this scope even if it's no longer "active" (e.g. when the function it was created for returns). The "inner" function was created in a scope which contained a loopIndex variable, set to the value of i at the time the IIFE was called. So when you try to reference a variable named loopIndex from inside the inner function, it first checks its own scope (and doesn't find a loopIndex there) then starts walking up its scope chain - first, it checks the scope in which it was defined, which does contain a loopIndex variable, the value of which is passed to console.log().

这就是一个封闭的 - 它可以访问在它被定义范围的功能,即使在功能范围创建为已完成执行

That's all a closure is - a function which has access to the scope in which it was defined, even if the function the scope was created for has finished executing.

这篇关于异步与异步的NodeJS调用响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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