only first object getting saved in javascript for loop

ⅰ亾dé卋堺 提交于 2019-12-13 03:55:10

问题


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);
        }
      });
    }

回答1:


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.



来源:https://stackoverflow.com/questions/26368957/only-first-object-getting-saved-in-javascript-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!