Question

function getNextID(number){
var maxKey = 0;
number = typeof number !== 'undefined' ? number : 1;

db.from('contributions').select('id').list().done(function(records) {

records.forEach(function(item){
    if (maxKey < item){
        maxKey = item;
    }
});

return(maxKey);

});

}

I am using ydn-db

This is a class for working with local storage - it works asynchronously, not AJAX!

What I am trying to do is get the next ID on a table (but that bit is the irrelevant part really).

The problem I am having is either:

a) I am an idiot and getting my scope wrong for maxKey

b) the asynchronous calls are messing everything up.

At the moment the function always returns 'undefined' - however if I replace return with console.log(maxKey); it works fine.

Can anyone tell me how I can fix this function so that it can be called correctly?

(it is an example function so although any built-in function for finding the next key would be appreciated I really need to know how to return asynchronous items from within a function!)

I hope that is clear - any questions - fire away!

Was it helpful?

Solution

function getNextID(number,callback){
var maxKey = 0;
number = typeof number !== 'undefined' ? number : 1;

db.from('contributions').select('id').list().done(function(records) {

records.forEach(function(item){
    if (maxKey < item){
        maxKey = item;
    }
});

callback(maxKey);

});

}

then in your code

getNextID(number,function(maxKey){
   // continue the code here.
});

since your code is async you cant return anything from getNextID but a promise or use a continuation (a callback).

OTHER TIPS

Since primary key are sorted, you can get the maximum key just by taking the first one:

function getNextID(number,callback){

var key_range = number ? ydn.db.KeyRange.lowerBound(number, true) : null;

var reverse = true; // sort by descending order
var iter = new ydn.db.KeyIterator('contributions', key_range, reverse);

db.get(iter).done(function(maxKey) {

  callback(maxKey);

});

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top