最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - return null value in node.js? - Stack Overflow

programmeradmin2浏览0评论

I am new in nodejs. Here is my code in nodejs file. i want to send data from nodejs to other javascript use json.stringify,but my problem is i get null value... ----------------EDIT-----------------------

my code is

function handler ( req, res ) {
        calldb(dr,ke,function(data){
            console.log(data); //successfully return value from calldb                                      
        });
    //i think my problem bellow...
    res.write( JSON.stringify(data)); //send data to other but it's null value
    res.end('\n');
}

function calldb(Dr,Ke,callback){
    // Doing the database query
    query = connection.query("select id,user from tabel"),
        datachat = []; // this array will contain the result of our db query
    query
    .on('error', function(err) {
        console.log( err );
    })
    .on('result', function( user ) {
        datachat.push( user );
    })
    .on('end',function(){
        if(connectionsArray.length) {
            jsonStringx = JSON.stringify( datachat );
            callback(jsonStringx); //send result query to handler
        }
    });

}

How to fix this problem?

I am new in nodejs. Here is my code in nodejs file. i want to send data from nodejs to other javascript use json.stringify,but my problem is i get null value... ----------------EDIT-----------------------

my code is

function handler ( req, res ) {
        calldb(dr,ke,function(data){
            console.log(data); //successfully return value from calldb                                      
        });
    //i think my problem bellow...
    res.write( JSON.stringify(data)); //send data to other but it's null value
    res.end('\n');
}

function calldb(Dr,Ke,callback){
    // Doing the database query
    query = connection.query("select id,user from tabel"),
        datachat = []; // this array will contain the result of our db query
    query
    .on('error', function(err) {
        console.log( err );
    })
    .on('result', function( user ) {
        datachat.push( user );
    })
    .on('end',function(){
        if(connectionsArray.length) {
            jsonStringx = JSON.stringify( datachat );
            callback(jsonStringx); //send result query to handler
        }
    });

}

How to fix this problem?

Share Improve this question edited May 4, 2013 at 9:29 ltvie asked May 4, 2013 at 3:44 ltvieltvie 9734 gold badges21 silver badges49 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You will need to use callbacks, returning data directly will just return null because the end event handler is called later when all the data is ready. Try something like :

function handler ( req, res ) {
    calldb(dr, ke, function(data){
       console.log(data);
       res.write( JSON.stringify(data)); 
       res.end('\n');
    });
}

function calldb(Dr,Ke, callback) { 

    var query = connection.query('SELECT id,userfrom tabel'),
        datachat= []; // this array will contain the result of our db query

    query
     .on('error', function(err) {
        console.log( err );
     })
     .on('result', function( user ) {
        datachat.push( user );
     })
     .on('end',function() {
        callback(datachat);
    }); 

}

The problem is that nodejs is asynchronous. It will execute your res.write( JSON.stringify(data)); before your function will be called. You have two options: one to avoid callback:

    .on('end',function(){
      if(connectionsArray.length) {
        jsonStringx = JSON.stringify( datachat );
        res.write( JSON.stringify(data)); 
        res.end('\n');
      }
    }

the other have the response in the callback function like this:

function boxold() {
  box(function(data) {
        res.write( JSON.stringify(data)); 
        res.end('\n');
        //console.log(data);
  });
}
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>