Sunday 11 June 2017

Priority of commands using javascript

I am currently doing a project of databse connection using NodeJS and MongoDB. I am new to JavaScript (I have been reading tutorials for the last 2 weeks).

My issue here is that I can't a portion of code after being connected to the database. I am pretty sure I didn't understood something about callbacks and/or priority (and it might be because my only use of calbacks was while working on VxWorks for a real-time application project, where you had to tell which callback was priority to each others).

Here is my code so far :

var MongoClient = require('mongodb').MongoClient;
var Connected = false;

// Connection is a function to connet to the mongodb database
function Connection() {
    // Connection
    MongoClient.connect("mongodb://localhost/test", function(err, db) {
        if (err) throw err;
        else {
            // characters becomes the collection with which we can do things
            var characters = db.collection("characters");
            // Proof of connection
            Connected = true;
            console.log("Succesful database connection\n");
        }
    });
}


function randomname(callback) {
    console.log("Program started\n");

    callback();

    if(Connected) {console.log(typeof(characters));}
}

randomname(Connection);

The behaviour of this code is supposed to be the following :

  1. Connect to the mongodb database
  2. Store the collection in the characters var
  3. do things using the characters var (ultimately doing a .find() request, but I just wanted to show the type of characters for simplicity here)

If you could help me or at least give me specific documentation about the behaviour of this language while using callbacks I would be very thankful.

_Nauth



via A. Duhamel

No comments:

Post a Comment