0

I'm using formidable (github) and I'm not sure about the scope of some variables inside the callbacks. Part of my code is:

UploadHandler.prototype.upload = function(req, res){
    var query = url.parse(req.url, true).query;
    var form = new formidable.IncomingForm();
    var id = query['X-Progress-ID'];

    self.uploads.add(id);

    form.parse(req, function(err, fields, files){
        self.uploads.remove(id);
        res.writeHead(200, { 'Content-type': 'text/plain' });
        return res.end('upload received');
    });

    ...

}

My question is, what will be the value of id inside the callback of parse? Also, will that code work as expected if more than 1 person is uploading a file? (As in, will id change it's value for both the first and the second person if they're both using the uploader at the same time.

1 Answer 1

2

id is what you defined and yes, it will work if there's more than one call to upload : the id variable is local to the invocation of the upload function. The scope here is the function call which forms what's called a closure.

Here's a simplified version of your code :

function upload(i){
   var id=i; // id is local to the invocation of upload
   setTimeout(function(){ console.log(id) }, 100*i);
}
for (var i=0; i<3; i++) {
    upload(i);
}

It logs 0, 1, 2.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.