stackoverflow kerdes

stackoverflow kerdes

by JayData

HTML

<script src="http://include.jaydata.org/jaydata.js"></script>
<a href="#" id="doit">do it</a>

JavaScript

$data.define("Type1", {
  Id: 'int',
  ParentId : 'int'
});

var db = $data.EntityContext.extend('db', {
  MySplDB: { type: $data.EntitySet, elementType: Type1 }
});

var myDB = new db({name: 'indexedDb', databaseName: 'test11181111'});

function drop() {
    console.log('start dropping');
    return myDB.MySplDB
    .toArray()
    .then(function(x) {
        x.forEach(function(xx) {
            myDB.MySplDB.remove(xx);
        });
        console.log('before drop saveChanges');
        return myDB.saveChanges();
    });
}

function fill() {
    for (i=0; i<10000;i++) {
        var pid = Math.ceil(Math.random() * 1000000);
        myDB.MySplDB.add(new Type1({ParentId: pid}));
        if (i%1000 == 0) console.log(i);
    }
    return myDB.saveChanges();
}

var l = [];
function getData(idValue) {
    return myDB.MySplDB
    .filter( function(val) {
        return val.ParentId == this.parentId;
    }, {parentId: idValue})
    .toArray()
    .then(function(vals) {
        if(vals.length < 1) {
            // some operation to store the value
            l.push(idValue);
            return true;
        } else {
            var promise = getData(vals.shift().Id);
            while (vals.length > 0) {
                promise = promise.then(function(){ return getData(vals.shift().Id) });
            }
            return promise;
        }
    });
}

function doit() {
    myDB.onReady()
    .then(drop)
    .then(fill)
    .then(function() {
        l = [];
        getData(1)
        .then(function() {
            console.log('over', l);
        })
        .fail(function(reason) {
            console.log(reason);
        });
    });
}

$('#doit').click(doit);