Node.js和Express:异步操作后如何返回响应 [英] Node.js and Express: How to return response after asynchronous operation

查看:307
本文介绍了Node.js和Express:异步操作后如何返回响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js的新手,所以我仍然围绕着异步函数和回调。我现在的奋斗是如何在异步操作中从文件读取数据后返回响应。

I'm new to Node.js, so I'm still wrapping my head around asynchronous functions and callbacks. My struggle now is how to return a response after reading data from a file in an asynchronous operation.

我的理解是发送响应就像这样(这适用于我):

My understanding is that sending a response works like this (and this works for me):

app.get('/search', function (req, res) {
    res.send("request received");
});

但是,现在我想读取一个文件,对数据执行一些操作,然后返回导致回应。如果我想对数据执行的操作很简单,我可以做这样的事情 - 内联执行它们,并保持对 res 对象的访问,因为它仍然在范围内。

However, now I want to read a file, perform some operations on the data, and then return the results in a response. If the operations I wanted to perform on the data were simple, I could do something like this -- perform them inline, and maintain access to the res object because it's still within scope.

app.get('/search', function (req, res) {
    fs.readFile("data.txt", function(err, data) {
        result = process(data.toString());
        res.send(result);
    });
});

但是,我需要执行的文件操作很长很复杂,我已将它们分开了在一个单独的文件中放入自己的函数。因此,我的代码看起来更像是这样:

However, the file operations I need to perform are long and complicated enough that I've separated them out into their own function in a separate file. As a result, my code looks more like this:

 app.get('/search', function (req, res) {
    searcher.do_search(res.query);
    // ??? Now what ???
});

我需要调用 res.send in为了发送结果。但是,我不能直接在上面的函数中调用它,因为 do_search 是异步完成的。我无法在 do_search 的回调中调用它,因为 res 对象不在那里。

I need to call res.send in order to send the result. However, I can't call it directly in the function above, because do_search completes asynchronously. And I can't call it in the callback to do_search because the res object isn't in scope there.

有人可以帮我理解在Node.js中处理这个问题的正确方法吗?

Can somebody help me understand the proper way to handle this in Node.js?

推荐答案

要访问不同函数中的变量,当没有共享范围时,将其作为参数传递。

To access a variable in a different function, when there isn't a shared scope, pass it as an argument.

你可以传递 res 然后在一个变量中访问查询发送函数。

You could just pass res and then access both query and send on the one variable within the function.

出于分离关注点的目的,你可能最好不要再传递回调。

For the purposes of separation of concerns, you might be better off passing a callback instead.

然后 do_search 只需知道执行查询然后运行函数。这使得它更通用(因此可重复使用)。

Then do_search only needs to know about performing a query and then running a function. That makes it more generic (and thus reusable).

searcher.do_search(res.query, function (data) {
    res.send(...);
});

function do_search(query, callback) {
    callback(...);
} 

这篇关于Node.js和Express:异步操作后如何返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆