简体   繁体   中英

Javascript promises loading in reverse order

I am trying to upload a picture as well as some other data, which is captured from a form, to my Parse database. A lot of this code is copied from the Parse Javascript guide. The name, price and description details upload fine, but the picture never uploads. What I get on my log is:

adding item...

Item sucessfully added!

Item sucessfully uploaded!

In that order... I'm not sure why this would happen especially since i'm using the whole promise paradigm. Why would the item be added before the image is uploaded? And why isn't this 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 to 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 was some error.
            alert("Saving item failed with error code " + error.message);
        }
    )
);

return false;

}

.then() takes functions as arguments. In your second .then() you want to pass a function to be called when the promise is resolved. Instead you are actually calling the function and passing the results to then.. so that function gets called before the first promise resolves. Also, you should return a promise from your first .then() . I think the 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 was some error.
        alert("Saving item failed with error code " + error.message);
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM