Javascript 承诺以相反的顺序加载

Javascript promises loading in reverse order

我正在尝试将图片以及从表单捕获的一些其他数据上传到我的 Parse 数据库。很多代码是从 Parse Javascript 指南中复制的。名称、价格和描述详细信息上传正常,但图片从未上传。我在日志中得到的是:

adding item...

Item sucessfully added!

Item sucessfully uploaded!

按照这个顺序......我不确定为什么会发生这种情况,特别是因为我使用的是整个承诺范例。为什么要在上传图片之前添加项目?为什么这段代码不起作用?

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() 将函数作为参数。在您的第二个 .then() 中,您想要传递一个函数,以便在承诺得到解决时调用。相反,您实际上是在调用该函数并将结果传递给 then.. 因此该函数在 第一个承诺解决之前被调用。此外,您应该 return 第一次 .then() 的承诺。我认为以下应该有效:

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