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);
        }
      });
    }
2
  • 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. Commented Oct 14, 2014 at 19:41
  • 1
    var messages = new Messages; is only one Object since it's not inside the loop. Commented Oct 14, 2014 at 19:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

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.