2

I want to access k and error value inside and outside a function. I had initialized the value for k as 0 and error as an empty string. But the console.log("executed") is printed.

var  k = 0;
var error = "";

const { teamname, event_name, inputcount, name, roll } = req.body;
function check1(teamname, event_name, callback) {
    Register.find({ teamname: teamname, eventname: event_name }, (err, docs) => {
        callback(docs.length)
    });
}
check1(teamname, event_name, function (e) {
    if (e != 0) {
        console.log("executed");
        k = 1
    }
});
console.log(k) // 0
console.log(error) // undefined
fiza khan
  • 1,280
  • 13
  • 24
Rajendran bala
  • 87
  • 1
  • 11

1 Answers1

2

You can declare global variables using NodeJS global object. But in your case, you want the k to be 1, but it's 0. because NodeJS is asynchronous, you should console.log(k) inside the callback.

When you run this program, the console.log(k) and console.log(error) executes before the check1 function returns the value to the callback. That's asynchronous process. so you are getting k as 0. In order to solve it, you should console.log inside the callback

var k = 0;
var error = "error";

const { teamname, event_name, inputcount, name, roll } = req.body;
function check1(teamname, event_name, callback) {
        Register.find({ teamname: teamname, eventname: event_name }, (err, docs) => {
            callback(docs.length)
        });
    }
    check1(teamname, event_name, function (e) {
       if (e != 0) {
            console.log("executed");
            k = 1
       }
       console.log(k) // prints 0 or 1
       console.log(error) // prints "error"
    });

https://stackabuse.com/using-global-variables-in-node-js/

Nithya Rajan
  • 4,722
  • 19
  • 30
  • In my code 10 th line I had updated the value `k` as `1`, but still the value is printed as `0`.sure the part is executed and in console `executed` line is also printed but the k value is not updating – Rajendran bala Mar 02 '19 at 05:04
  • try again now i have changed the global object to var variable – Nithya Rajan Mar 02 '19 at 05:06
  • I had seen your updated post, is there is any possibility to change the asynchronous as synchronous – Rajendran bala Mar 02 '19 at 05:07
  • 1
    https://stackoverflow.com/questions/9884418/how-can-i-make-this-call-to-request-in-nodejs-synchronous this answer might help you. – Nithya Rajan Mar 02 '19 at 05:12
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/189290/discussion-between-rajendran-bala-and-bear-nithi). – Rajendran bala Mar 02 '19 at 05:13