我试图解决节点js中一个需要rad文件的编程问题。用qio做这件事的正确方法是什么?
这是我的节目
var express = require('express')
var qfs = require('q-io/fs')
var q = require('q')
var fs = require('fs')
var app = express()
app.get('/books', function(req, res){
qfs.read(process.argv[3])
// .then( function(buf){res.json(JSON.parse(buf))})
// .done()
.then(res.send).done()
/* .then(null, function(abc, err){
res.json(err)
console.log("Error handler")
res.status(500)
})*/
})
app.listen(process.argv[2])我知道我可以同步读取文件,下面的代码也可以工作
qfs.read(process.argv[3])
.then( function(buf){res.json(JSON.parse(buf))})
.done()但是主代码会产生错误,我理解这是因为app对象已经超出了范围,因为请求处理程序可能已经返回了。
/home/ubuntu/mahesh/node_tries/node_modules/q/q.js:155
throw e;
^
TypeError: Cannot read property 'req' of undefined
at send (/home/ubuntu/mahesh/node_tries/node_modules/express/lib/response.js:103:17)
at _fulfilled (/home/ubuntu/mahesh/node_tries/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/home/ubuntu/mahesh/node_tries/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/home/ubuntu/mahesh/node_tries/node_modules/q/q.js:796:13)
at /home/ubuntu/mahesh/node_tries/node_modules/q/q.js:604:44
at runSingle (/home/ubuntu/mahesh/node_tries/node_modules/q/q.js:137:13)
at flush (/home/ubuntu/mahesh/node_tries/node_modules/q/q.js:125:13)这里发生了什么??当调用express.js时,res.end的处理程序在什么时候返回?
发布于 2016-03-28 10:21:30
有点晚了,但我自己偶然发现了这个问题,想帮助将来遇到这个问题的人。
在response.js中,程序失败的行是这样的:
var req = this.req;当调用res.send()时,使用res的上下文调用函数send (因此"this“是res),而this.req是request对象。
但是,当您将函数作为变量传递给允诺时,它失去了上下文,变成了一个函数。因此,当它被调用时,"this“是未定义的,this.req变成了一个错误。因此,要解决问题,请替换
.then(res.send).done()使用
.then(books => res.send(books)).done()https://stackoverflow.com/questions/33080832
复制相似问题