Parse.com的嵌套承诺

时间:2015-11-09 09:10:07

标签: javascript parse-platform promise

我有一个函数用Parse的promise

逐个更新数据库行
exports.update = function (items, successHandler, errorHandler) {

    Parse.Cloud.useMasterKey();
    var Item = Parse.Object.extend("Item");

    Parse.Promise.as().then(function () {
        var promises = [];

        for (var i = 0; i < items.length; i++) {                
                (function (j) {  //create new closure so i changes with each callback
                    var query = new Parse.Query(Item);
                    query.equalTo("sku", items[j]['sku'];);

                    promises.push(query.find({
                        success: function (results) {
                            if (results.length === 1) {
                                var object = results[0];

                                console.log('Item exists, now updating..');

                                return object.save(items[j]).then(function () {
                                    console.log("Item saved"); // never called, why?

                                }, function (error) {
                                    console.error("Item not saved with error: " + error.message); // never called, why?
                                });
                            }
                        },
                        error: function (error) {
                            console.error("Failure during querying..");
                        }
                    }));
                })(i);
        }

        return Parse.Promise.when(promises);

    }).then(function () {
            return successHandler("Item updated.");
        }, function (error) {
            return errorHandler(error);
        }
    );
};

问题是,实际调用了object.save并且数据正在保存在数据库中,但是,从不调用以下两个承诺,无论是否成功。

1 个答案:

答案 0 :(得分:0)

我认为,因为你从内在成功功能中回归的承诺不一定会得到满足。您最好使用query.find()代替

宣传.then()功能
promises.push(query.find().then(function(results) {

     if (results.length === 1) {
         var object = results[0];

         console.log('Item exists, now updating..');

         return object.save(items[j]);
    }

    }).then(function() {
         console.log("Item saved"); 

    }, function (error) {
         console.error("Item not saved with error: " + error.message); 
    });

}));