Execution order is not followed

2

I'm using this library to run IndexedDB functions more easily:

Dexie

But the code does not follow the order of execution in any way and this causes my script to not work.

Example

This code is just an example to show that it does not follow the order of execution, where you can observe the browser console while refreshing the page:

View in JSFiddle .

var db = new Dexie('teste');
var atual_sequence = 0;

db.version(1).stores({sequences: '++id,of'});

db.open().catch(function(error){
});

db.sequences.where("of").equalsIgnoreCase('0').count(function (count) {
  atual_sequence = count;
  console.warn(atual_sequence);

});
db.sequences.add({of: '0'});

console.log('ds: '+atual_sequence);

It runs console.log('ds: '+atual_sequence); before getting the sequence number, is there any way to fix this?

    
asked by anonymous 03.04.2015 / 02:40

1 answer

3

As explained in that other answer , the problem is that this library is doing asynchronous operations, so that they still have not finished running at the time the subsequent code is called. A simple and straightforward solution would be to move all the code after the asynchronous call to the callback of it:

db.sequences.where("of").equalsIgnoreCase('0').count(function (count) {
    atual_sequence = count;
    console.warn(atual_sequence);

    // Movida pra dentro do callback
    db.sequences.add({of: '0'});

    console.log('ds: '+atual_sequence);
});

Example . Another alternative - if this solution is to make your code too messy - is to use then , because the count function returns a promise ( Promise ):

db.sequences.where("of").equalsIgnoreCase('0').count(function (count) {
    atual_sequence = count;
    console.warn(atual_sequence);
}).then(function() {

    db.sequences.add({of: '0'});

    console.log('ds: '+atual_sequence);
});

Example 2 .

    
03.04.2015 / 07:41