Nodejs MySQL connection query return value to function call

前端 未结 1 1824
眼角桃花
眼角桃花 2020-12-21 15:43

I am trying get value from database. Trying it out with a demo example. But I am having problem to synchronize the calls, tried using callback function. I am beginner in nod

相关标签:
1条回答
  • 2020-12-21 15:56

    The issue is this:

    var r = db.demo(query, function(result) { data = result; });
    
    console.log( 'Data : ' + data);
    

    The console.log will run before the callback function gets called, because db.demo is asynchronous, meaning that it might take some time to finish, but all the while the next line of the code, console.log, will be executed.

    If you want to access the results, you need to wait for the callback function to be called:

    var r = db.demo(query, function(result) { 
      console.log( 'Data : ' + result);
    });
    

    This is how most code dealing with I/O will function in Node, so it's important to learn about it.

    0 讨论(0)
提交回复
热议问题