0

I am new to Javascript and Nodejs so this question might sound very basic.I am trying to fetch the value returned from promise elsewhere. I tried using getter method and also tried using global variable and assigning it to the local variable to fetch it but I still have difficulties.

    var initCounter = 0;
    function sql_count() {
    sql_connection.User.count().then(function (count) {
        if(count) {
         initCounter= count; //-> I would like to get the value of count.
         console.log(initCounter);
         return initCounter;
        }

    });
};
  • Simply add `return` before `sql_connection....`. *"tried using global variable"* That's almost always the wrong way to go about it. – Felix Kling Aug 24 '17 at 18:39
  • @FelixKling thanks for your reply. I did that already but the problem is it returns an object but what I want is the value. This code is to check the number of rows in a table. If I am wrong can you please help me? – bhuvanesh arasu Aug 24 '17 at 18:46
  • You are performing an async operation. `sql_count` will return a promise and you can get the value by doing `sql_count().then(value => { /* do something with value */ })`. If the caller is currently expecting the value synchronously then you have to refactor the code to make it work asynchronously. You cannot make the async code synchronous. – Felix Kling Aug 24 '17 at 18:50

0 Answers0