database - Javascript promises loading in reverse order -


i trying upload picture other data, captured form, parse database. lot of code copied parse javascript guide. name, price , description details upload fine, picture never uploads. on log is:

adding item...

item sucessfully added!

item sucessfully uploaded!

in order... i'm not sure why happen since i'm using whole promise paradigm. why item added before image uploaded? , why isn't code working?

function additem() {     console.log('adding item...');     var item = parse.object.extend("fooditem");     var newitem = new item(); newitem.set("createdby", parse.user.current()); newitem.set("name",$('#itemname').val()); newitem.set("price",parseint($('#itemprice').val())); newitem.set("description",$('#itemdescription').val());  //upload pic parse cloud  var fileuploadcontrol = $("#itemimage")[0]; if (fileuploadcontrol.files.length > 0)  {     var file = fileuploadcontrol.files[0];     var name = "photo.jpg";     var parseimage = new parse.file(name, file); }  parseimage.save().then (     function()      {         newitem.set(name,parseimage);         console.log("image sucessfully uploaded!");         return;     } ).then (     newitem.save().then     (          function()         {             console.log("item sucessfully added!")         },         function(error)          {         // there error.             alert("saving item failed error code " + error.message);         }     ) );  return false; 

}

.then() takes functions arguments. in second .then() want pass function called when promise resolved. instead calling function , passing results then.. function gets called before first promise resolves. also, should return promise first .then(). think following should work:

parseimage.save().then(function() {     newitem.set(name,parseimage);     console.log("image sucessfully uploaded!");     return newitem.save(); }) .then(function() {         console.log("item sucessfully added!")       },       function(error) {          // there error.         alert("saving item failed error code " + error.message);       }); 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -