我正在按照教程制作图像上传系统。
现在下面的函数用于上传,它使用了外部模块formidable
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
fs.rename(files.upload.path, "/tmp/test.png",
function(error) {
if (error) {
fs.unlink("/tmp/test.png");
fs.rename(files.upload.path, "/tmp/test.png");
}
});
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
form.parse 接受 2 个参数,request 和一个新函数,但新函数接受 3 个新参数。
我好像看不懂。这 3 个新论点从何而来?与外部库有关还是我没有正确理解 JavaScript?
提前致谢。
最佳答案
form.parse
有 2 个参数,第二个参数是调用 callback
的函数。回调从 form.parse
实现中获取参数。
让我们用更简单的例子来解释:
function foo(callback) {
var arg1 = 10;
var arg2 = 'string';
var arg3 = false;
// call function with args
callback(arg1, arg2, arg3);
};
function callback(num, str, bool) {
// we get args from foo implementation
console.log(num);
console.log(str);
console.log(bool);
}
foo(callback);
在 foo
代码中,我们使用 3 个参数调用 callback
。现在我们可以在 callback
函数中使用它们
关于javascript - 不理解新函数的参数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600713/