javascript - 在express应用程序中异步执行res.render

标签 javascript node.js express asynchronous router

我尝试使该路由器响应异步:

var express = require('express'),
    router  = express.Router();

router.get('/', function(req, res, next) {
  res.render('contact', {
    titleShown: true,
    title: 'Contact'
  });
});

我尝试实现我读到的async here ,但不工作:

var express = require('express'),
    router  = express.Router(),
    async   = require('async');

router.get('/', function(req, res, next) {
  async.parallel([
    res.render('contact', {
      titleShown: true,
      title: 'Contact'
    })
  ], req);
});

我怎样才能做到这一点?

使用 --trace-sync-io 标志时收到的错误消息:

WARNING: Detected use of sync API
    at fs.statSync (fs.js:892:18)
    at tryStat (C:\www\node\website\node_modules\express\lib\view.js:169:15)
    at resolve (C:\www\node\website\node_modules\express\lib\view.js:142:14)
    at lookup (C:\www\node\website\node_modules\express\lib\view.js:110:17)
    at View (C:\www\node\website\node_modules\express\lib\view.js:85:20)
    at render (C:\www\node\website\node_modules\express\lib\application.js:569:12)
    at render (C:\www\node\website\node_modules\express\lib\response.js:961:7)
    at C:\www\node\website\routes\contact.js:9:7
    at handle (C:\www\node\website\node_modules\express\lib\router\layer.js:95:5)

最佳答案

不,res.render 并不是完全异步的(目前)。所以错误确实来自 res.render:

Yes, there are sync parts of the res.render API (which sucks), but it will be addressed in Express 5.0, as we cannot address it without breaking the view engine compatibility.

Starting your application with NODE_ENV=production or setting the cache to true for rendering will cause file system activities only once per view at startup, which makes this a non-issue while the application is fully running in production, since no sync file systems are called since the views are cached.

Source

关于javascript - 在express应用程序中异步执行res.render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36282413/

相关文章:

javascript - HTML 文件找不到外部 javascript 函数

javascript - 错误 : Cannot find module 'xml2json'

node.js - 在连接路由器中获取请求对象

javascript - nodeJS 异步与同步

javascript - 在 javascript 中动态显示带有 for 循环换行符的警告框

javascript - raphael.js 中的拖动约束和缩放

javascript - 无法使用第 3 方 API 出现错误,因为请求的资源上不存在 'Access-Control-Allow-Origin' header

node.js - 使用 mongoose 更新 MongoDB 文档时出现问题

javascript - Angular2 指令分配给模板

php - API 服务器框架的选择