简体   繁体   中英

Why modify request after request.post

Newbie question while trying to understand code created by others. Believe me I tried to understand this. Here goes..

For what reason would someone still call functions like .qs() and .json() in Request - module after we got what we need with .post() and sent the response already. They can't affect the request.post as they are called afterwards, can they?

With my skills I'm not able to understand from response module API docs (v2.22.0) what these actually do.

This is not the whole code but I tried to get the important parts here:

// When request comes to /getthisapge, make external query and return data in JSON format.
var request = require('request');
module.exports = function(app) {
  app.get('/getthispage', function(req, res, next) {
    var filter = {};
    var query = {};
    filter.category = req.query.category;
    query.onBehalf = req.query.onBehalf;
    request.post(URIandoptions, function(error, response, body) {
      res.json(body.members)
    }).qs(query).json(filter);
  }
}

Without knowing exactly what the post function does (unnecessary to your question), you need to look at the order of execution.

request.post(URIandoptions, function (error, response, body){ 
    res.json(body.members) 
}) 
.qs(query)        //  ?
.json(filter);    //  ?

The function passed into post() does not get called at that specific moment. It is given to the post() function to do with as it pleases. This means technically that the function may never be called (depends on the api).

qs() and json() both get called upon the returning of the prior function. Usually this type of api means the following:

  • call post() , passing in a function to be run on completion
  • call qs() to setup the query details
  • call json() to tell the post function how to act, which in turn executes the actual post, running the completion function after data has been retrieved.

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