node.js中间件使代码同步 [英] node.js middleware making code synchronous

查看:71
本文介绍了node.js中间件使代码同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在每个页面上提供 res.locals.info .我正在尝试通过中间件执行此操作,但出现错误.当页面呈现时,显然res.locals.info尚未准备就绪,因此我收到错误消息 info is not defined .我该如何解决?

I am trying to make res.locals.info available on every single page. I'm trying to do this by middleware but I'm getting an error. Apparently res.locals.info is not ready yet when the page render, thus I get an error info is not defined. How do I solve this?

  app.use(function(req,res,next){

  async function getInfo(user) {

    let result = await info.search(user);
    setInfo(result);
  }

function setInfo(result){

  res.locals.info= result;
}
getInfo(req.user);

  return next();
})

search():

module.exports.search= function (user) {
    var query=`SELECT count(*) as Info from dbo.InfoUsers WHERE user= '${user}' ;`

    return new Promise((resolve, reject) => {
    sequelize
        .query(`${query}`, {model: InformationUser})
        .then((info) => {

        resolve(info);
        })
    })
};

推荐答案

您在 getInfo()函数完成其工作之前正在调用 next(),因此<尝试使用code> res.locals.info 时尚未设置.

You were calling next() before your getInfo() function had done its work, thus res.locals.info had not yet been set when you were trying to use it.

async 函数返回一个Promise.在完成 await 之前,它不会阻塞.相反,它会立即返回一个承诺.您将需要在 getInfo()上使用 await .then(),这样才能知道它何时真正完成.

An async function returns a promise. It does NOT block until the await is done. Instead, it returns a promise immediately. You will need to use await or .then() on getInfo() so you know when it's actually done.

如果 info.search()返回的承诺可以解决所需的结果,则可以执行以下操作:

If info.search() returns a promise that resolves to the desired result, then you could do this:

app.use(function(req,res,next){

  // this returns a promise that resolves when it's actually done
  async function getInfo(user) {
    let result = await info.search(user);
    setInfo(result);
  }

  function setInfo(result){
    res.locals.info= result;
  }

  // use .then() to know when getInfo() is done
  // use .catch() to handle errors from getInfo()
  getInfo(req.user).then(result => next()).catch(next);

});

而且,您可以从其中删除递延反模式您的搜索功能并修复错误处理(使用反模式时这是一个常见问题).无需将现有的承诺包装在另一个承诺中.

And, you can remove the deferred anti-pattern from your search function and fix the error handling (which is a common issue when you use the anti-pattern). There is no need to wrap an existing promise in another promise.:

module.exports.search = function (user) {

    var query=`SELECT count(*) as Info from dbo.InfoUsers WHERE user= '${user}' ;`
    // return promise directly so caller can use .then() or await on it
    return sequelize.query(`${query}`, {model: InformationUser});
};

这篇关于node.js中间件使代码同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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