0

I have been looking for a solution to this problem but have come up empty. It seems that some people have similar issues, however they have syntax errors that make their problem easy to correct.

I am defining an array and then below where the array is defined, I have a method. The method has a forEach that I am pushing objects into the array. When console logging the array is fully populated within the loop, but once outside of the loop, the array is empty again. Below is my code snippet

var arr = [];

function getObjects(context, done) {
request(request).then((objs) => {
    objs.result.forEach((obj) => {

        var obj = {
            key1: med.medication,
            key2: med.timeOfDosage1,
            key3: med.timeOfDosage2
        }

        arr.push(obj) 
       console.log(arr)//console.log shows array full of objects
    })
  })
};

console.log("The new arr array: " ,arr) //console.log shows empty array
jorgehjr84
  • 11
  • 1
  • 1
  • 4
    It seems you have an `asynchronous` operation, which means that your array will be filled when that async op completes. When you do the console.log at the bottom, the async op hasn't completed yet and hence your array is empty. – JohanP Mar 09 '17 at 01:29
  • This code looks like it is using a Promise to manage the request. You can [read up on this here](http://stackoverflow.com/documentation/javascript/231/promises). – rasmeister Mar 09 '17 at 01:35
  • It's not about being outside of the `forEach` callback, it's about being outside of the `then` callback, and - even worse - outside of the `getObjects` function that isn't called at all. – Bergi Mar 09 '17 at 01:56

0 Answers0