mr.loop
mr.loop

Reputation: 1005

Nodejs script executing without waiting for Mongodb query

I have the following part in a nodejs file

client.db('metro4').collection('Station').findOne({"Name": variabled2}, function(err, res2) {
        if(err) throw err;
        variabled2 = res2._id;
        console.log("id2 = ", res2._id);
    });

console.log("v= ",variabled2);

myFunc(variabled);

the myFunc function also has some mongodb queries.

The problem is in the order of execution.

v = undefined
then some of function results (which are obviously wrong)
id2 = 4
then other of functions results

I came from running MySQL queries inside node and there weren't these problems even in long stored procedures.

Now many answers suggested 'async and await'. So, I made myFunc async & tried this

(async function() {
        await recur2();
    })();

But as expected the result are nearly same as the program is not waiting for first query.

Also, I discovered .then() like Promises but they apparantly don't work when having callback function like I have in my query above.

Thanks in advance.

Upvotes: 0

Views: 424

Answers (1)

Cheng Dicky
Cheng Dicky

Reputation: 518

The first query is using callback so it won't wait for its completion. So what you need is await the first query, or place myFunc into the callback.

place inside callback

let variabled2;
client.db('metro4').collection('Station').findOne({"Name": variabled2}, 
    function(err, res2) {
        if(err) throw err;
        variabled2 = res2._id;
        console.log("id2 = ", res2._id);

        myFunc(variabled);
    });

async/await

(async function() {
    let variabled2;
    const res2 = await client.db('metro4').collection('Station').findOne({"Name": variabled2})
    variabled2 = res2._id;
    console.log("id2 = ", res2._id);
    myFunc(variabled);
})()

I would suggest the async/await solution as it is cleaner.

Upvotes: 1

Related Questions