Query + httpRequests =许多承诺无法正常工作

时间:2014-08-10 16:55:59

标签: parse-platform httprequest

我有一个简单的代码:有一个查询,在这个查询中,对于每个项目,我做一个httpRequest并且这个请求保存数据 我的问题是:如何在完成云代码之前完成所有承诺/请求/保存。

var query = new Parse.Query(Readers);
query.find({
    success: function(readersList) {
        for(var qi = 0; qi < readersList.length; qi++) {
            promises.push(Parse.Cloud.httpRequest({
                url: '......',
                success: function(httpResponse) {
                    var Post = Parse.Object.extend("Post");
                    var resultList = httpResponse.data.data.items;
                    for(var hRi = resultList.length; hRi > 0 ; hRi--) {
                        post.save();
                    }
                }
            }));
            break;
        }
        Parse.Promise.when(promises).then(function(){
            response.success("All Readers Done!");
        });
    }
});

修改

模式详细代码:

query.find().then(functions(results) {

    var promises = [];

    for(var ri = results.length; ri > 0 ; ri--) {

        var promise = Parse.Cloud.httpRequest({
            url: results[ri]
        }).then(function (httpResponse) {
            var Post = Parse.Object.extend("Post");
            var resultList = httpResponse.data.data.items;
            var savePromises = [];
            for(var hRi = resultList.length; hRi > 0 ; hRi--) {
                // not sure what "post" is in this context?
                savePromises.push(post.save());
                savePromises.push(results[ri].save());

            }
            // wait for all saves to finish
            return Parse.Promise.when(savePromises);
        });
        promises.push(promise);
    }

    return Parse.Promise.when(promises);

}).then(function() {
    //success
});

提前致谢:)

编辑2 我的目的是:在查询之后,迭代这些元素,并为每个元素发出对请求的HTTP请求。根据此Feed的结果,我将检查数据库中是否已存在该项目,然后保存/更新项目。

1 个答案:

答案 0 :(得分:0)

您遇到的问题是您要向数组中添加Parse.Cloud.httpRequest()承诺,但没有任何内容等待post.save()。您可以将其链接以获得所需的结果:

var promise = Parse.Cloud.httpRequest({
    url: '....'
}).then(function (httpResponse) {
    var Post = Parse.Object.extend("Post");
    var resultList = httpResponse.data.data.items;
    var savePromises = [];
    for(var hRi = resultList.length; hRi > 0 ; hRi--) {
        // not sure what "post" is in this context?
        savePromises.push(post.save());
    }
    // wait for all saves to finish
    return Parse.Promise.when(savePromises);
});
promises.push(promise);