简体   繁体   中英

How do you pass variable to callback function?

New to node, express, and javascript.

Below is code in my index.js in routers folder.

I want to pass along or access res variable in handleImport function.

function handleImport( err, stat)
{
  if(err == null) {
    // Do something with res
    res.end();
  }
  else{
    // Do something with res
    res.end();
  }
}


router.get('/traveler', function(req, res, next) {
    var import_path = req.query.drawing;
    fs.stat(import_path,handleImport);
});

It appears bind() may be what I'm after but cannot find a good source for how to use it correctly.

AFAICS, the best solution is to use anonymous function.

router.get('/traveler', function(req, res, next) {
    var import_path = req.query.drawing;

    fs.stat(import_path, function (err, stat) {
        if (err == null) {
            // Do something with res
            res.end();
        } else {
            // Do something with res
            res.end();
        }
    });
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM