在云代码

时间:2015-09-29 20:09:30

标签: javascript json parse-platform cloud-code

我正在编写一些从第三方API中提取JSON的Parse Cloud Code。我想修改它,检查它是否已经存在,如果没有,保存它。在检查对象是否存在后,我遇到了麻烦。

这是我想要做的一个例子。当我到达成功块时,我需要原始的汽车对象,以便我可以将它保存到解析数据库中。虽然它未定义。我是JS的新手,我可能在这里遗漏了一些明显的东西。

for (var j = 0, leng = cars.length; j < leng; ++j) {
    var car = cars[j];          
    var Car = Parse.Object.extend("Car");
    var query = new Parse.Query(Car);           
    query.equalTo("dodge", car.model);
    query.find({
      success: function(results) {
          if (results.length === 0) {
            //save car... but here car is undefined.
          } 
      },
      error: function(error) {
        console.error("Error: " + error.code + " " + error.message);
      }
    });
 }

如果有人能指出正确的方向,我会非常感激。谢谢!

2 个答案:

答案 0 :(得分:1)

您的函数在find方法返回之前返回。这是js的异步性质。使用async lib中的async.parrallel之类的东西。 http://npm.im/async

更新20150929:

这里有一些代码向您展示我是如何做到的,这是来自我正在进行的一个侧面项目。数据存储在MongoDB中,并使用Mongoose ODM进行访问。我正在使用Async瀑布,因为我需要在下一个方法中使用异步函数的值...因此在异步库中名称为waterfall。 :)

 async.waterfall([
    // Get the topics less than or equal to the time now in utc using the moment time lib
    function (done) {
        Topic.find({nextNotificationDate: {$lte: moment().utc()}}, function (err, topics) {
            done(err, topics);
        });
    },
    // Find user associated with each topic
    function (topics, done) {
        // Loop over all the topics and find the user, create a moment, save it, 
        // and then send the email.
        // Creating moment (not the moment lib), save, sending email is done in the 
        // processTopic() method. (not showng)
        async.each(topics, function (topic, eachCallback) {
                processTopic(topic, eachCallback);
            }, function (err, success) {
                done(err, success);
            }
        );
    }
    // Waterfall callback, executed when EVERYTHING is done
], function (err, results) {
    if(err) {
        log.info('Failure!\n' + err)
        finish(1); // fin w/ error
    } else {
        log.info("Success! Done dispatching moments.");
        finish(0); // fin w/ success
    }
});

答案 1 :(得分:1)

一旦你习惯了,承诺将真正简化你的生活。这是使用promises的更新或创建模式的示例...

function updateOrCreateCar(model, carJSON) {
    var query = new Parse.Query("Car");
    query.equalTo("model", model);
    return query.first().then(function(car) {
        // if not found, create one...
        if (!car) {
            car = new Car();
            car.set("model", model);
        }
        // Here, update car with info from carJSON.  Depending on
        // the match between the json and your parse model, there
        // may be a shortcut using the backbone extension
        car.set("someAttribute", carJSON.someAttribute);
        return (car.isNew())? car.save() : Parse.Promise.as(car);
    });
}

// call it like this
var promises = [];
for (var j = 0, leng = carsJSON.length; j < leng; ++j) {
    var carJSON = carsJSON[j];
    var model = carJSON.model;
    promises.push(updateOrCreateCar(model, carJSON));
}
Parse.Promise.when(promises).then(function() {
    // new or updated cars are in arguments
    console.log(JSON.stringify(arguments));
}, function(error) {
    console.error("Error: " + error.code + " " + error.message);
});