Do not understand the arguments of a new function as an argument

advertisements

I am following a tutorial to make an upload system for images.

Now the following function is used for uploading, and it uses the external module 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 takes 2 arguments, request and a new function but the new function takes 3 new arguments.

I can't seem to understand it. Where do these 3 new arguments come from? Has it to do with the external library or do I not understand JavaScript correctly?

Thanks in advance.


form.parse take 2 args, second arg is function called callback. Callback get arguments from form.parse implementation.

Let explain on more simple example:

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);

In foo code we call callback with 3 args. Now we can use them in callback function