【问题标题】:Is Array.forEach in Node.js asynchronous?Node.js 中的 Array.forEach 是异步的吗?
【发布时间】:2017-07-19 04:32:40
【问题描述】:

数组上的 forEach 是异步的吗? candies 是一个糖果对象数组。

app.get('/api/:id',function(req, res){

  console.log("Get candy");
  var id = req.params.id;

  candies.forEach( function(candy, index){
    if(candy.id == id){
      console.log("Candy found. Before return");
      return res.json(candy);
      console.log("Candy found. After return");
    }
  });

  console.log("Print error message");
  return res.json({error: "Candy not found"});
});

在控制台中我得到

[nodemon] starting `node app.js`
listning on port 3000
Get candy
Candy found. Before return
Print error message
Error: Can't set headers after they are sent.
   at ServerResponse.setHeader (_http_outgoing.js:367:11)
   ....

这是最近的变化吗?自从我完成 node.js 以来已经有一段时间了

【问题讨论】:

  • 为什么return后面有代码?
  • 如果它是异步的,您将首先记录Print error message。为什么会是异步的?此外,Thilo 正确指出了 - return 语句之后的代码有什么意义?那永远不会被执行。
  • 另外,内部函数中的return只会退出内部函数,不会退出外部函数。
  • 啊,我们走了……当然!完美的解释了它。我今天一定想不通。谢谢@Thilo!

标签: javascript arrays node.js nodes


【解决方案1】:

您收到 Can't set headers after they are sent. 异常是因为您尝试两次返回响应 - (可能)一次在 candies.forEach 内,另一次在路线的最后一行。另请注意,return 之后的任何代码无论如何都不会执行。

这是你如何重写它以避免错误 -

app.get('/api/:id',function(req, res){

    console.log("Get candy");
    var id = req.params.id;
    var foundCandy = false;
    candies.forEach( function(candy, index){
        if(candy.id == id){
            foundCandy = true;
            console.log("Candy found. Before return");
        }
    });

    if (foundCandy) {
        return res.json(candy);
    } else {
        return res.json({error: "Candy not found"});
    }
});

【讨论】:

  • @Jens 使用Array.filter 就像@Vladu Ionut 的回复here 也可以使代码更简洁。
  • 谢谢!我知道如何解决它。我只是好奇为什么我会得到这种行为。 res.json(candy) 和 res.json({error: "Candy not found"});得到调用。这对我来说似乎不合逻辑,除非 forEach 现在是一个异步函数
  • 知道了...见@Thilo 回复
【解决方案2】:

你可以使用Array.filter找到糖果。

app.get('/api/:id', function(req, res) {

  console.log("Get candy");
  var id = req.params.id;

  var result = candies.filter(candy => candy.id == id);

  if (result.length) {
    return res.json(result[0]);
  } else {
    console.log("Print error message");
    return res.json({
      error: "Candy not found"
    });
  }
});

【讨论】:

  • 致所有关注这个问题的人:“return res.json(candy);”仅从 forEach 参数中定义的内部函数返回,而不是从整个函数返回。两个响应都会被调用。
猜你喜欢
  • 2012-09-27
  • 2011-07-04
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 2014-03-20
  • 2016-03-01
相关资源
最近更新 更多