Execution order is not followed

Asked

Viewed 787 times

2

I am using this library to perform Indexeddb functions more easily:

Dexie

But the code does not in any way follow the execution order and that makes my script does not work.

Example

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

See on the 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);

He executes the console.log('ds: '+atual_sequence); before obtaining the sequence number, is there any way to correct this?

1 answer

3

As explained in that other answer, the problem is that this library is doing asynchronous operations, so that they have not yet finished executing by the time the later code is called. A simple and straightforward solution would be to move all code after the asynchronous call to the callback of the same:

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 the then, for the function count 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.