0

On parse.com, Im trying to save an object which includes:

  • a message body,
  • the senders name,
  • the senders id,
  • and the recipients name

    to a class called "Messages." The object is getting saved correctly, however, when i try to use a for loop in order to save 3 different copies each with a different and random recipient, only the first object gets saved.

randUsers is an array with three random users.

How do i fix this?

function sendLean(leanBody, leanSenderName, leanSenderId, randUsers){
    var Messages = Parse.Object.extend("Messages");
    var messages = new Messages();
    for(var i = 0; i < 3; ++i){

      messages.set("messageBody", leanBody);
      messages.set("recipientId", randUsers[i]);
      messages.set("senderName",  leanSenderName);
      messages.set("senderId", leanSenderId);

      messages.save(null, {
        success: function(messages) {
          // Execute any logic that should take place after the object is saved.
          alert('New object created with objectId: ' + messages.id);
        },
        error: function(messages, error) {
          // Execute any logic that should take place if the save fails.
          // error is a Parse.Error with an error code and message.
          alert('Failed to create new object, with error code: ' + error.message);
        }
      });
    }
ian
  • 1,002
  • 2
  • 12
  • 29
  • 2
    without seeing what the Messages object looks like, I would suggest instantiating the object _inside_ your for loop instead of modifying the properties on each pass of the loop. – dfperry Oct 14 '14 at 19:41
  • 1
    `var messages = new Messages;` is only one Object since it's not inside the loop. – StackSlave Oct 14 '14 at 19:46

1 Answers1

2

You need each new instance of your Messages object to be inside your for loop. Change

var messages = new Messages();
for(var i = 0; i < 3; ++i){

to

for(var i=0,l=randUsers.length; i<l; i++){
  var messages = new Messages;

if randUsers is an Array, or

for(var i in randUsers){
  var messages = new Messages;

if randUsers is an Object.

StackSlave
  • 10,613
  • 2
  • 18
  • 35