-1

i am new to nodejs,i wrote a function like this:

function getResult(){
    var result='';
    //do something asynchronous,like query datebase and assign result
    db.query(sql,function(err,res){
        if(err) throw err;
        result=res;
    })
    return result;
}

i run it

getResult();

but i can't get result. it seems to be the function return before the asynchronous steps .

can i waiting for the asynchronous steps done,and then let the function return ?how? thanks..

solo
  • 13
  • 3
  • research callbacks... – Jakub Dec 23 '13 at 02:24
  • You can't wait for asynchronous commands to finish. You can only subscribe to their completion. A good write-up using Ajax for the example is "[How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)" But, you'll want to define `getResult()` to either accept its own `callback` to be called or return something like a `Promise` that can be resolved when `res` is available. – Jonathan Lonowski Dec 23 '13 at 02:25

2 Answers2

0

by using callbacks. This is one of the core concepts of javascript.

function getResult(callback){
    var result='';
    //do something asynchronous,like query datebase and assign result
    db.query(sql,function(err,res){
        if(err) throw err;
        callback(res);
    })
}

use this function with

getResult(function(res){
// do something
});
tn4foxxah
  • 287
  • 2
  • 11
0

it's an easy issue, but it contains an important concept in node.js. let's look at this: your code :

  function getResult(){
    var result='';
    //do something asynchronous,like query datebase and assign result
    db.query(sql,function(err,res){
      if(err) throw err;
       result=res;
    })
    return result;
  }

it runs like this: firstly, do

db.query (sql)

then, it may do

return result

directly. because when the query operation is done, it will do

function(err, res){ ...}

so, you may get the answer you want, may not. how to fix this? you can use callback like this:

function getResult(callback){
  db.query (sql, function(err, res){
     if (err) throw err;
     callback res;
  });
}  

getResult(function(result){ 'do something you like with result' });

may it will help you!

allen wang
  • 1,087
  • 2
  • 7
  • 16