0

I am writing a function that updates an array outside the scope of the function and the array does not update with the new values added

  var eventArray = [];

  function findStuff(){
    query.find({
      success: function(results) {
        for (var i = 0; i < results.length; i++) {
          var eventObject = {};
          eventObject["id"] = results[i].id
          eventObject["name"] = results[i].get("name")
          eventArray.push(eventObject)
          console.log(eventObject)
      }
      eventArray = JSON.stringify({ "data":eventArray})
      console.log(eventArray)
      },
        error: function(error) {
        console.log("Error: " + error.code + " " + error.message);
      }
    });
  }

  findStuff();
  console.log(JSON.stringify({ "data":eventArray}))
Adim
  • 811
  • 2
  • 10
  • 25
  • The `.find()` operation is **asynchronous**. The "success" function is called when the operation completes, and that will happen some time *after* the `.find()` call itself returns. It starts the operation but does not wait for it to finish, in other words. – Pointy Mar 19 '15 at 13:11
  • @pointy So how do I fix this? How can I use the array after it finishes updating? – Adim Mar 19 '15 at 13:12
  • 1
    Do it *inside* the "success" callback - the whole point of that callback is to allow you to schedule work to be done when the operation completes. – Pointy Mar 19 '15 at 13:13
  • I actually need to get the info out of the callback, is this possible? I have a function I need the values for outside the .find(). I need them returned really but I cannot find a way to do this – Adim Mar 19 '15 at 13:17
  • No, it's not possible. Look at the question & answers linked as a duplicate of this one. You have to change the structure of the application: instead of expecting functions like this to return values, you design them to allow callbacks to be passed in. – Pointy Mar 19 '15 at 13:21

0 Answers0