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

javascript - node.js sending a response from a callback - Stack Overflow

programmeradmin1浏览0评论

I am using the express framework to handle requests. Some of the steps involve invoking asynchronous functions. Eventually I would like the return the value puted in one of these functions.

app.post("/hello", function(req, res) {
    ...
    ...

    myFunc(finalFantasy);
}

function myFunc(callback) {
    ...
    callback();
}

function finalFantasy() {
    //I want to return this value in the response
    var result = "magic";
}

How can I use the value calculated in finalFantasy function in the response?

I am using the express framework to handle requests. Some of the steps involve invoking asynchronous functions. Eventually I would like the return the value puted in one of these functions.

app.post("/hello", function(req, res) {
    ...
    ...

    myFunc(finalFantasy);
}

function myFunc(callback) {
    ...
    callback();
}

function finalFantasy() {
    //I want to return this value in the response
    var result = "magic";
}

How can I use the value calculated in finalFantasy function in the response?

Share Improve this question asked Dec 18, 2013 at 17:35 dopplesoldnerdopplesoldner 9,49912 gold badges46 silver badges57 bronze badges 1
  • With the code structure identical to shown in the question, just make myFunc return the result of callback - and use it. – raina77ow Commented Dec 18, 2013 at 17:38
Add a ment  | 

4 Answers 4

Reset to default 3

You have to pass the res instance to the callback, or use callback like the second example.

app.post("/hello", function(req, res) {
...
...

myFunc(finalFantasy, req, res);
}

function myFunc(callback, req, res) {
...
callback(req, res);
}

function finalFantasy(req, res) {
//I want to return this value in the response
var result = "magic";
res.end(result);
}

Another example is this:

app.post("/hello", function(req, res) {
    ...
    ...
    var i = 3;

    myFunc(i, function(data) {
        res.end(data); // send 4 to the browser
    });
}

function myFunc(data, callback) {
    data++; //increase data with 1, so 3 bee 4 and call the callback with the new value
    callback(data); 
}
app.post("/hello", function(req, res) {
    ...
    ...

    var result = myFunc(finalFantasy);
}

function myFunc(callback) {
    ...
    return callback();
}

function finalFantasy() {
    //I want to return this value in the response
    var result = "magic";
    return result;
}

you almost had it, just like @raina77ow said in the ment, pass the result back up

Keep passing res along, and in your final "response generating function", send data to it. The general way to do this with express is to use the middleware cascade, storing persistent values in res.locals:

app.get("/", function(req, res, next) {
  // do things
  next();
},function(req, res, next) {
  // do more things
  next();
},function(req, res, next) {
  // do even more things!
  next();
},function(req,res) {
  // and finally we form a response
  res.write(things);
});

Although you normally put this in a middleware file and then include that, calling its functions:

// middleware "lib/functions.js" file
module.exports = {
  a: function(req, res, next) { ... },
  b: function(req, res, next) { ... },
  c: function(req, res, next) { ... }
}

and then in your app.js, main.js, or similarly obvious main file:

var mylib = require("./lib/functions");
...
app.get("/", mylib.a, mylib.b, mylib.c);
...

done. Nice and organised, and automatic passthrough of streams through the next concept.

// wrap finalFantasy using an anonymous function

app.post("/hello", function(req, res) {
    ...
    ...
    myFunc(function () {
         var ret = finalFantasy();
         res.send(ret);
    });
}

function myFunc(callback) {
    ...
    callback();
}

function finalFantasy() {
    //I want to return this value in the response
    var result = "magic";
}
发布评论

评论列表(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; } ?>