1

I have an array of images as this.

  var newImageParams = [
    {
      image_string: "hello",
      _type: "NORMAL"
    },
    {
      image_string: "hello",
      _type: "NORMAL"
    }
  ]

I am using mongo db and In nodejs, I am using mongoose, Everything is fine, I Can add data to mongoose table, but after adding each image, I am trying to save the resulting object into an array, Which in console.log is happening and right as well, but when I return that array, there is nothing in it and it empty

if (newImageParams) {
  for (var i = newImageParams.length - 1; i >= 0; i--) {
    // allImages[i]
    var newImage = new Image(Object.assign(newImageParams[i], {bike: bike._id}));
    newImage.save(function(err, image){
      console.log(image);
      allImages.push(image);
      console.log(allImages);
    });
  }
}

This is what I am doing, everything is right and good in console but when I finally return,

res.json({bike: bike, images: allImages });

Images array is totally empty as it was when declared? why this is happening, please help

1
  • post the full code block Commented Jul 17, 2017 at 14:45

2 Answers 2

2

I bet you send response before your callbacks are done.

The easy and fast fix:

if (newImageParams) {
  for (var i = newImageParams.length - 1; i >= 0; i--) {
    const image = Object.assign(newImageParams[i], {bike: bike._id});
    var newImage = new Image(image);
    allImages.push(image);
    newImage.save(function(err, image){
      console.log(image);
      console.log(allImages);
    });
  }
}

I will add correct approach with async/await, the older versions would use Promise.all or async.parallel:

async function doJob() {
  if (newImageParams) {
    for (var i = newImageParams.length - 1; i >= 0; i--) {
      const image = Object.assign(newImageParams[i], {bike: bike._id});
      const newImage = new Image(image);      
      await newImage.save();
      allImages.push(image);
    }
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

why cant we add the actual image object to array?
@JunaidFarooq I've updated my answer, hope this will help you understand the issue.
where to add and call this method?
Can you specify, what node version you have? Or maybe you can update it to latest?
v6.11.1 here you go
|
0

allImages.push(image); -> that line of code is async. It's will go to event queue and your console log will call immediately.

So console.log(allImages); will return empty.

You can read more in here. It will help you in future.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.