在 forEach nodeJS 之后发送响应

Sending response after forEach nodeJS

我正在 NodeJS 中开发一个 API,它只会在 foreach 循环完成并在循环内完成每个操作的结果后发送响应。 现在的问题是代码没有等到 foreach 完成发送响应。

要求:

  "enterpriseName": "myEnterprise",
  "channels": [
    {
      "provider": "mail",
      "contact": "11111111111",
      "configuration": [
        {
          "name" : "token",
          "value" :"1234567890"
        }
      ]
    },
    {
      "provider": "phone",
      "contact": "123456789",
      "configuration": [
        {
          "name" : "access_token",
          "value" :"987654321"
        }
      ]
    }
  ]
}

代码:

app.post('/channelEnterprise', (req, res) => {
    var output = [];
    checkEnterpriseByName(req.body.enterpriseName, knex).then((exist) => {
        if (exist) {
            req.body.channels.forEach(channel => {
                addChannel(req.body.enterpriseName, channel, knex).then((channelEnterpriseId) => {
                    output.push({'provider' : channel.provider,
                                 'Id': channelEnterpriseId[0],
                                 'result': 'ok'
                    })                  
                    res.json(output)                    
                });             
            });             
        }else{
            res.status(500).send({ error: 'Enterprise' + req.body.enterpriseName + ' does not exist. Try to create previous the enterprise and then add the channel' });
        }   
    })
})

目标: 目标是 运行 res.json(output) 仅当 foreach 已完成类似这样的事情时:

[
    {
        "provider": "mail",
        "Id": 15,
        "result": "ok"
    },
    {
        "provider": "phone",
        "Id": 16,
        "result": "ok"
    }

]

您应该使用 map 函数而不是 foreach,并使用 Promise.all 来等待 map。另外,使用 async/await 以获得更好的体验。

试试这个

app.post('/channelEnterprise',async (req, res) => {
   const exist = await checkEnterpriseByName(req.body.enterpriseName, knex);
if (exist) {
  let output = [];
  await Promise.all(
    req.body.channels.map(async channel => {
      const channelEnterpriseId = await addChannel(
        req.body.enterpriseName,
        channel,
        knex
      );
      output.push({
        provider: channel.provider,
        Id: channelEnterpriseId[0],
        result: 'ok',
      });
    })
  );
  res.json(output);
} else {
  res.status(500).send({
    error:
      'Enterprise' +
      req.body.enterpriseName +
      ' does not exist. Try to create previous the enterprise and then add the channel',
  });
}
})