0

I have a background job as follows:

Parse.Cloud.job('checkProjectStatus', function(req, res) {
    var Project = Parse.Object.extend('Project');
    var projectQuery = new Parse.Query(Project);
    projectQuery.find().then(function(projects) {
        var promises = [];

        for(var i = 0; i < projects.length; i++) {
            var p = projects[i];
            promises.push(
                Parse.Cloud.httpRequest({
                    url: p.get('link').trim()
                }).then(function(httpResponse) {
                    console.log(httpResponse.text);
                    p.set('status', httpResponse.status);
                    return p.save();
                }, function(httpResponse) {
                    console.log('HTTP RESPONSE TEXT: ' + httpResponse.text);
                    p.set('status', httpResponse.status);
                    return p.save();
                })
            );
        }
        return Parse.Promise.when(promises);
    }).then(function() {
        res.success("DONE!");
    });
});

The intended processing of the above background job is to fetch every object from Project class and make a httpRequest to the value of field "link" in it. Then save whatever response code is returned in the corresponding Project object. My code is just updating one object that too wrong. Can someone tell me what is wrong in the above code and guide me for a right code?

XCEPTION
  • 1,671
  • 1
  • 18
  • 38

1 Answers1

1

I'm not familiar with Parse but I think your issue is an example of a closure inside a loop : see JavaScript closure inside loops – simple practical example

Replacing the the code inside promises.push() with promises.push(makePromise(p)) where makePromise is as follows

var makePromise = function (p) {
    return Parse.Cloud.httpRequest({
                url: p.get('link').trim()
            }).then(function(httpResponse) {
                console.log(httpResponse.text);
                p.set('status', httpResponse.status);
                return p.save();
            }, function(httpResponse) {
                console.log('HTTP RESPONSE TEXT: ' + httpResponse.text);
                p.set('status', httpResponse.status);
                return p.save();
            })
};

should fix your problem.

You could also leave your code as is and use let instead of var in your loop depending on which browsers you need to support. let is not yet widely supported.

You would have let p = projects[i] instead of var p = projects[i].

Community
  • 1
  • 1
user5325596
  • 2,310
  • 4
  • 25
  • 42