Async save of RSS feed

by JayData

HTML

<script src="http://include.jaydata.org/jaydata.js"></script>

JavaScript

$( document ).ready(function() {
   
    
    $data.define('PNRFeed', {
        FeedId: { type: String, key: true, computed: false },
        FeedName: String,
        ImageName: String
    });
    
    $data.define('PNRFeedItem', {
        FeedItemId: { type: String, key: true, computed: false },
        FeedId: String,
        PostName: String,
        PostUrl: String,
        PostDate: String
    });
    
    $data.EntityContext.extend("PNRDatabase", {
        PNRFeeds: { type: $data.EntitySet, elementType: PNRFeed },
        PNRFeedItems: { type: $data.EntitySet, elementType: PNRFeedItem }
    });
    
    var pnrDB = new PNRDatabase("PnrDb");
    
    pnrDB.onReady(function () {    
        $.ajax({
            dataType: "json",
            url: "http://www.plugnrun.com/api/MobileFeeds",
            async: false,
            success: function (data) {
                var lfeedtop = 5;
                
                //declaration of recursive loop
                var loop = function(max, curr){
                    saveIfNotExists(data[curr],curr)
                        .then(function(r){ //this is running when the promise.resolve() is called
                            console.log(curr+". item is "+r);
                            if(max>curr){
                                //recursive call
                                loop(max,curr+1);
                            }else{
                                //save new elements only after the end of the loop
                                pnrDB.saveChanges();
                            }
                        });                    
                };
                
                var saveIfNotExists = function(feed,idx){
                    //create jQuery promise
                    var def = new $.Deferred();
                    //async thread 
                    pnrDB.PNRFeeds.filter('it.FeedId == ' + feed.FeedID).count(function (count) {
                        console.log(feed.FeedID + ' - ' +...