簡體   English   中英

在雲代碼中解析查詢后保留對象

[英]Retaining objects after parse query in cloud code

我正在編寫一些Parse Cloud代碼,該代碼可從第三方API中提取JSON。 我想修改它,檢查它是否已經存在,如果不存在,請保存它。 在檢查對象是否存在后,我很難保留它。

這是我正在嘗試做的一個例子。 當我到達成功塊時,我需要原始的汽車對象,以便可以將其保存到解析數據庫中。 雖然沒有定義。 我是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);
      }
    });
 }

如果有人能指出正確的方向,我將不勝感激。 謝謝!

您的函數將在find方法返回之前返回。 這是js的異步特性。 使用類似異步庫中的async.parrallel之類的東西。 http://npm.im/async

更新20150929:

這是一些代碼,向您展示我是如何做到的,這是我正在做的一個輔助項目。 數據存儲在MongoDB中,並通過Mongoose ODM訪問。 我正在使用異步瀑布,因為在下一個方法中需要異步函數的值...因此,異步庫中的名稱為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
    }
});

一旦習慣了,諾言將真正簡化您的生活。 這是一個使用諾言的更新或創建模式的示例...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM