In JavaScript, I'm attempting to build an HTML table using data retrieved from a MongoDB. However, I'm having trouble with the asynchronisity of the MongoDB calls.
Below is my code where I'm building the HTML to insert into a table.
The problem is that once I'm in the callback, I have no idea how to update the assets string that's outside the scope of my callback function.
var assets = "";
assets += "<tr><td class='groupHeading'>Bank Accounts and Cash</td></tr>";
var MongoClient = require('mongodb').MongoClient;
var URL = 'mongodb://localhost:27017/alta';
MongoClient.connect(URL, function(err, db) {
if (err) return;
var collection = db.collection('account');
collection.find().toArray(function(err, docs) {
==> // How do I get the values from the docs array back to my assets string???
db.close();
})
})
assets += "<tr><td></td><td class='balanceUnderline'><hr/></td></tr>";
assets += "<tr><td class='groupTotal'>Total Bank Accounts and Cash</td><td class='balanceCol'>10,000.00</td></tr>";
document.getElementById('AssetsTable').innerHTML = assets;
EDIT: I read through the duplicate question, but it doesn't seem to answer my question. In that question, the OP specifically states, "Why does it output undefined in all of these examples? I don't want workarounds, I want to know why this is happening."
In my case, I know what's happening, but don't know how to get what I want.
In the duplicate question answers/examples, the callback does the entire work with the data being passed. In my case, I need to do the following:
- Init the data
- Call the async function - that manipulates the data
- After the callback finishes, modify the data still more.
Unless I missed it or didn't understand it, I didn't find an answer to that in the duplicate question.