0

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:

  1. Init the data
  2. Call the async function - that manipulates the data
  3. 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.

  • 2
    *"After the callback finishes, modify the data still more."* You can call another function inside the callback and pass the modified data to it. Any code that needs the data has to be either *inside* or *called from* the callback. – Felix Kling Jun 10 '16 at 01:16
  • @FelixKling Thanks! Re-reading that a few times finally resonated with me, and I was able to fix my code. –  Jun 10 '16 at 02:36
  • 1
    @TomArcher I used to put in `console.log` statements throughout various chunks of code so I could see what order things ran in. That really helped me get used to things and verify things. – Jeremy J Starcher Jun 10 '16 at 02:43

0 Answers0