I use Dexie.js (an IndexedDb
wapper).
I've tried generating HTML like this:
function getList(where){
var html = [];
if($.isEmptyObject(where)) return;
db.modules.where(where).each(function(item){
html.push('<div class="module-item">');
html.push('<div class="module-item-pic"><img src="' + item.modu_pic + '" class="img-fluid" /></div>');
....
html.push('</div>')
html.push('</div>');
})
console.log(html.join(''));
}
but the code above outputs nothing.
However, I get an output when I put console.log(html.join(''))
inside the callback to .each
:
function getList(where){
var html = [];
if($.isEmptyObject(where)) return;
db.modules.where(where).each(function(item){
html.push('<div class="module-item">');
html.push('<div class="module-item-pic"><img src="' + item.modu_pic + '" class="img-fluid" /></div>');
....
html.push('</div>')
html.push('</div>');
console.log(html.join(''));
})
}
Why is my first code snippet failing to show any output?
Remember that Dexie operations are generally asynchronous. The problem is that your first code snippet executes console.log(html.join(''))
immediately, before any of the asynchronous operations are done.
You need to use the promise returned by .each
to wait until all iterations are complete before trying to output to the console:
function getList(where){
var html = [];
if($.isEmptyObject(where)) return;
db.modules.where(where).each(function(item){
html.push('<div class="module-item">');
html.push('<div class="module-item-pic"><img src="' + item.modu_pic + '" class="img-fluid" /></div>');
....
html.push('</div>')
html.push('</div>');
}).then(function () {
console.log(html.join(''));
});
}