Nadine
Nadine

Reputation: 357

How to send an array with Express res.send()

I created this api to send back an array which I filled with data:

router.get('/getDevice/:instanceId', (req, res) => {
    let deviceSum = [];
    SingleAxis.findAll({where: {instanceid: req.params.instanceId}})
        .then(singleAxis => {
            if (singleAxis) {
                for (let i = 0; i < singleAxis.length; i++) {
                    SingleAxisSegment.findAll({where: {singleAxisId: singleAxis[i].singleAxisId}})
                        .then(singleAxisSegments => {
                            let sum = 0;
                            for (let i = 0; i < singleAxisSegments.length; i++) {
                                sum += singleAxisSegments[i].counterAmount;
                            }
                            deviceSum.push({label: singleAxis[i].name, value: sum});
                        })
                        .catch(err => {return err});
                }
                console.log(deviceSum);
                res.status(200).send(deviceSum);
            } else {
                res.status(200).json({message: 'Nothing found'});
            }
        })
        .catch(err => res.status(400).json({message: 'Error', err}));
});

The console.log(deviceSum) prints out the following data:

[
  { label: 'Z5', value: 4404253 },
  { label: 'X9', value: 4423724 },
  { label: 'D6', value: 5506045 }
]

So the array contains data but when I test the api with a rest client I just get an empty array back.

How can I send the array back to the client?

Upvotes: 1

Views: 3805

Answers (1)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

You have to send the response inside the second findAll method. You are sending response before completing the second findAll promise.

Could you try this code.

I have used async await to make the code more readable.

router.get("/getDevice/:instanceId", async (req, res) => {
  let deviceSum = [];
  try {
    let singleAxis = await SingleAxis.findAll({
      where: { instanceid: req.params.instanceId }
    });
    if (singleAxis) {
      for (let i = 0; i < singleAxis.length; i++) {
        let singleAxisSegments = await SingleAxisSegment.findAll({
          where: { singleAxisId: singleAxis[i].singleAxisId }
        });
        let sum = 0;
        for (let i = 0; i < singleAxisSegments.length; i++) {
          sum += singleAxisSegments[i].counterAmount;
        }
        deviceSum.push({ label: singleAxis[i].name, value: sum });
      }
      console.log(deviceSum);
      res.status(200).send(deviceSum);
    } else {
      res.status(200).json({message: 'Nothing found'});
    }
  } catch (error) {
    res.status(400).json({ message: "Error", err });
  }
});


Upvotes: 4

Related Questions