我正在尝试调用 super 方法 save()
从子实例。
// ImageKeeper.js
'use strict';
module.exports = class ImageKeeper extends FileKeeper {
constructor(keeperPath, options) {
super(`/${keeperPath}`, options)
this.keeperPath = keeperPath;
}
save(filePath) {
return new Promise((resolve, reject) => {
this
.resolvePath(filePath)
.then(function(fileData) {
var filePath = fileData[0],
mime = fileData[1];
super.save(filePath, mime); // <-- GETTING ERROR HERE
})
.catch(function(err) {
reject(err)
})
})
}
}
// FileKeeper.js
'use strict';
module.exports = class FileKeeper {
constructor(keeperPath, options) {
this.storagePath = path.resolve(`${env.paths.storage}${keeperPath}`);
this.options = options;
}
save(filePath, mime) {
return Promise
...
}
}
我收到错误:
/src/filekeeper/imagekeeper.js:110
super.save(filePath, mime);
^^^^^
SyntaxError: 'super' keyword unexpected here
如果我搬家
super.save(filePath, mime);
在 save()
的开头方法,有效。我尝试将上下文绑定(bind)到上层范围:
save(filePath) {
return new Promise((resolve, reject) => {
this
.then((fileData) => { // <-- bind context to upper scope
super.save(filePath, mime);
但我得到:
Unhandled rejection SyntaxError: 'super' keyword unexpected here
at processImmediate [as _immediateCallback] (timers.js:374:17)
From previous event:
at /src/filekeeper/imagekeeper.js:106:10
阅读 this ,但没有运气。
有任何想法吗?谢谢你。
环境
root@8d1024b233c3:/src# node -v
v4.1.1
docker -v
Docker version 1.8.2, build 0a8c2e3
最佳答案
看起来您在 V8 处理 super
时发现了一个错误;我已经报告了这个错误 here他们将其分类为Type-Bug
和 Priority-Medium
.这是在仔细研究之后,导致我发帖 this question , 其中 this answer证实了我的怀疑,这是一个 V8 错误。
如果您按照“我已尝试将上下文绑定(bind)到上层范围”注释使用箭头函数(不是 function
函数)(主代码块正在使用 function
函数,它不起作用),它应该是在职的。
在等待修复时,如果您将该逻辑放入方法中,它会起作用:
someAppropriateName(fileData) {
var filePath = fileData[0],
mime = fileData[1];
super.save(filePath, mime);
}
...并从 Promise 回调中调用该方法:
save(filePath) {
return new Promise((resolve, reject) => {
this
.resolvePath(filePath)
.then(fileData => { // **
this.someAppropriateName(fileData); // **
}) // **
.catch(function(err) {
reject(err)
})
})
}
或者:
save(filePath) {
return new Promise((resolve, reject) => {
this
.resolvePath(filePath)
.then(this.someAppropriateName.bind(this)) // **
.catch(function(err) {
reject(err)
})
})
}
之所以可行,是因为该错误相当晦涩:仅当您在方法中的另一个箭头函数中具有箭头函数并且最内层的箭头函数使用由外部箭头函数定义的变量或参数时才会出现此错误(使用方法本身的东西)很好)。
不过,其他一些注意事项:
FileKeeper
的save
返回一个 promise ,看起来像 ImageKeeper
应该使用它并链接它。您的代码只是丢弃了调用 super.save(...)
的结果。 . new Promise
,总是停下来问问自己有问题的代码是否真的是链的根。非常非常非常经常不是(而且我怀疑它不在您的代码中)。请记住,每个 then
返回一个 promise,promise 的力量主要在于链。如果没有必要,不要打破链条。 关于inheritance - 在 Promise : 'super' keyword unexpected here? 中调用 super() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32932699/