【发布时间】:2016-09-05 09:03:13
【问题描述】:
我当前的代码是
resizer.resize(filepath, parsedUrl, fullDestinationPath, function() {
return self.send(response, 200, {'Content-Type': mime.lookup(fullDestinationPath)}, fs.createReadStream(fullDestinationPath));
});
调整大小运行到
Resizer.prototype.resize = function (filepath, parsedUrl, fullDestinationPath) {
this.read(filepath, parsedUrl, fullDestinationPath);
};
然后调用
Resizer.prototype.read = function(filepath, parsedUrl, fullDestinationPath){
something.then(function (somethingElse) {
// Not relevant for question
}).catch(function (err) {
console.error(err);
});
};
我在第二个代码 sn-p 中的this.read 之后有一个console.log(1);,以保证它完全通过它运行。但是回到我的第一个 sn-p 它不会调用我的回调。我在那里使用回调的原因是因为如果我不这样做,发送将在文件完全保存之前执行,除非它是一个非常小的文件,所以 self.send 需要在 .resize 之后调用,这就是为什么我我正在尝试使用回调。
我尝试了多种方法,认为语法错误可能是问题所在,或者它挂在某些东西上,但我已经验证它不是,它根本没有调用回调。我犯了某种明显的错误吗?如何让它调用回调?
我已阅读How to make a function wait until a callback has been called using node.js 之类的问题/答案,并了解它的工作原理并以相同的方式实现它,但它对我不起作用,我不明白为什么。感谢您花时间阅读本文。
编辑:在解决罗伯茨回答的问题后,我删除了回调并将代码更改为此,我使用承诺而不是回调: 片段 1:
resizer
.resize(filepath, parsedUrl, fullDestinationPath)
.then(function() {
return self.send(response, 200, {'Content-Type': mime.lookup(fullDestinationPath)}, fs.createReadStream(fullDestinationPath));
});
片段 2:
Resizer.prototype.resize = function (filepath, parsedUrl, fullDestinationPath) {
return this.read(filepath, parsedUrl, fullDestinationPath);
};
片段 3:
Resizer.prototype.read = function(filepath, parsedUrl, fullDestinationPath){
return Jimp.read(filepath)
.then(function() {
return //tons of irrelevant code
})
.catch(function (err) {
console.error(err);
});
};
【问题讨论】:
-
我没有看到任何回调被传递给您的调整大小函数或被您的调整函数使用。
-
返回 self.send 部分是未被调用的部分。你不是叫回调吗?同样使用console.log,我已经验证它正在运行所有代码并且没有挂在任何地方,它只是没有返回。 self 只是一个 var self = this;在代码的上部,因为当我在它周围放置另一个函数时,它的含义会发生变化。
-
self.send()是匿名函数定义中的命令,您将其作为参数传递给resize,但正如这里提到的,resize不接受其参数列表中的回调(它只接受文件路径、parsedUrl 和 fullDestinationPath)
标签: javascript node.js callback