我当前的代码是
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);
});
};
我在第二个代码片段中的 this.read
之后有一个 console.log(1);
以保证它完全通过它运行。但是回到我的第一个片段,它不会调用我的回调。我在那里使用回调的原因是因为如果我不这样做,发送将在文件完全保存之前执行,除非它是一个非常小的文件,所以 self.send
需要在之后调用.resize
这就是我尝试使用回调的原因。
我尝试了多种方法,认为语法错误可能是问题所在,或者它卡在某些东西上,但我已经证实它不是,它只是没有调用回调。我犯了一些明显的错误吗?如何让它调用回调?
我读过这样的问题/答案How to make a function wait until a callback has been called using node.js并了解它的工作原理并以相同的方式实现它,但它对我不起作用,我不明白为什么。感谢您花时间阅读本文。
编辑:在使用 Roberts answer 解决问题后,我删除了回调并将代码更改为此,我正在使用 promises 而不是回调: 片段 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);
});
};
最佳答案
Resizer.prototype.resize
不采用回调参数作为开始,因此即使您从主代码中传递了一个回调参数,也没有对其进行任何操作。
this.read()
也是如此:它也没有回调参数。
试试这个:
Resizer.prototype.resize = function (filepath, parsedUrl, fullDestinationPath, callback) {
this.read(filepath, parsedUrl, fullDestinationPath, callback);
};
和:
Resizer.prototype.read = function(filepath, parsedUrl, fullDestinationPath, callback){
something.then(function (somethingElse) {
callback(null, somethingElse);
}).catch(function (err) {
console.error(err);
callback(err);
});
};
关于javascript - 路由器应用程序的回调未调用 Node.Js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37137605/