我在es6中遇到一个奇怪的错误。 “ this”值不是
应该是,它使我无法在
中调用this._saveFile()下面的代码。
/**
* Performs the actions for saving the file.
* @param {[type]} data [description]
* @return {[type]} [description]
*/
_saveFile(data){
var p = new Promise((resolve,reject) => {
if(!isStream.readable(data.stream)){
reject("Data object must have a stream property that is a readable stream");
}
else if(typeof data.fileName !== 'string'){
reject("The fileName property is missing or malformed in the data object");
}
else{
let pool = ConnectionPool.getInstance();
pool.getConnection((err,conn) => {
if(err){
reject(err);
}
let m = new HackFileMapper(conn);
let dc = new DataConverter();
dc.streamToBase64(data.stream)
.then(base64Data => {
m.saveFile({
fileName:data.fileName,
fileData:base64Data
},{
sharerId:data.fields.sharerId,
shareeId:data.fields.shareeId
})
.then(fileId => {
conn.release();
resolve(fileId);
});
}).catch(reason => {
conn.release();
reject(reason);
});
});
}
});
return p;
};
/**
* Tries to handle the request as a save file request.
* If it can't then it passes the request to the
* next one in the chain.
*
* @param {[type]} request [description]
* @param {[type]} response [description]
* @return {boolean} True if the request was handled successfully,
* either by this handler or a handler further along the chain.
*/
handle(request, response){
var self = this;
var p = new Promise((resolve,reject) => {
if(typeof request === 'undefined' || request === null){
reject("The handle function must be passed a valid Request and Response object.");
}
else{ // try and process it.
var contentType = request.headers['content-type'];
if(contentType !== null &&
typeof contentType !== 'undefined' &&
contentType.indexOf('multipart/form-data') === 0){ // can it do it?
// handle it here.
parseFormdata(request,(err,data) => {
if(err){
SaveFileHandler._send400Response(response,"an error occurred parsing the forma data");
}
else if(data.parts.length < 1){
SaveFileHandler._send400Response(response,"No files sent");
}
else if(!data.fields.supplierId || !data.fields.customerId){
SaveFileHandler._send400Response(response,"supplerId and customerId must be included.");
}else{
this._saveFile(data).then(fileId => {
ConnectionPool.getInstance().getConnection((err,conn) => {
var m = new HackFileMapper(conn);
m.loadIcon(fileId).
then(icon => {
response.setHeader('content-type', 'application/json');
response.statusCode = 200;
response.end(JSON.stringify(icon));
resolve(true);
});
});
}).
catch(reason => {
SaveFileHandler._send400Response(response,reason);
});
}
});
}
else{ // pass it on.
self.successor.handle(request,response)
.then(result => resolve(result))
.catch(reason => reject(reason)); // for testing purposes.
}
} // else
});
return p;
}; // end fn.
当我使用npm test运行此程序时,我得到:
Uncaught TypeError: this._saveFile is not a function
at parseFormdata (src/request_handlers/SaveFileHandler.js:114:22)
at exports.Dispenser.internals.Dispenser.<anonymous> (node_modules/parse-formdata/index.js:43:20)
我尝试将“ this”放在函数前面以及存储
将“ this”引用为“ self”,也会出现相同的问题。
console.log(self)打印出与此无关的信息
班。这不是一个异步问题,必须是其他问题。
答案 0 :(得分:0)
在handle
中,您的箭头函数都正确地从外部块继承了this
,这意味着如果嵌套块中未正确引用this._saveFile
,{{ 1}}没有引用this
顶层的实例化对象。当您将函数作为回调传递而没有明确地handle
将其传递到预期的调用上下文时,可能会发生这种情况,例如:
bind
这里,您正在将var server = new HttpServer(handler.handle);
函数传递给构造函数,但没有handle
的调用上下文,这意味着当handler
调用回调,其HttpServer
不再引用this
。
handler
一种选择是使用const handler = {
handlerProp: 'handlerProp',
handle() {
console.log(this.handlerProp);
}
};
function invoker(callback) {
callback();
}
// Works:
handler.handle();
// Doesn't work:
invoker(handler.handle);
以确保在调用回调时,调用上下文符合预期:
.bind
另一种选择是传递具有适当调用上下文的调用 var server = new HttpServer(handler.handle.bind(handler));
的函数:
handler.handle
var server = new HttpServer(() => handler.handle());