问题
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