使用回调的Express.js执行流程 [英] Express.js execution flow using callbacks

查看:114
本文介绍了使用回调的Express.js执行流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对其中有对数据库的异步请求的express.js应用程序的执行流程非常怀疑. 我已经了解了Node.js架构,并且知道当我执行阻塞请求(如db请求)时,请求是在线程上执行的,当请求得到满足时,该线程将添加工作(回调函数的代码是为事件队列中的阻止请求指定的). 现在...由于我将mongoDb用作应用程序数据库,并且由于mongodb不提供执行同步请求的方法,因此如何确定在查询完成之前未执行对客户端的响应?

I have a huge doubt about the execution flow of an express.js application in which there are asynchronous requests to a database. I have read about the Node.js architecture and I know that when I perform a blocking request (like a db request) the request is performed on a thread that, when the request is satisfied, add work (the code of the callback function that was specified for the blocking request) on the event queue. Now... since I'm using mongoDb as application database and since mongodb doesn't provide methods for performing synchronous requests, how can I be sure that the response to the client is not performed before the query has been completed?

例如,在这种情况下,我有一个请求处理程序(不是中间件):

for example, in this situation in which I have a request handler (not a middleware):

app.all("/",function(req,res){

    db.find({},function(err,doc){

     //Retreive certain informations from the db needed by the client

    });
});

app.all("/",function(req,res){
   res.status(200).end();
});

这是使用express.js和mongodb的常见示例...

This is a common example of use of express.js and mongodb...

但是执行流程实际上是如何进行的?

But how the execution flow actually goes on?

对于中间件,我毫不怀疑,因为执行流程会一直停止,直到调用next()方法为止(您可以在数据库回调中调用它).

For the middlewares I don't have this doubt because the execution flow stops until the next() method is called (and you can call it inside the database callback).

预先感谢

路卡(Luca M.)

Luca M.

推荐答案

自从您提到next()以来,这里是如何链接中间件的基本示例:

Since you mentioned next() here is a basic example of how to chain middlewares:

function findInDb(id, callback){
  db.get(id, function(err, data){
    if(err){ return callback(err) };
    var obj = JSON.parse(data)[0] // or something
    callback(null, obj)
  });
};

app.all('*', function(req, res, next){
  findInDb('something', function(err, obj){
    if(err){ return next(err) };
    res.myObj = obj;
    next();
  });
});

app.get('/', function(req, res){
  // By now the first middleware executed
  res.status(200).json(res.myObject);
});

这篇关于使用回调的Express.js执行流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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