简体   繁体   中英

How to make http requests in my case?

I am trying to chain the http requests using NodeJs Request modules.

Example:

var options = {
  url: 'http://example.com'
};

request.get(options, function(error, response, body){
  var first = JSON.parse(body);

  options.url = 'http://example.com/second' + first.id;

  //nested second request
  request.get(options, function(error, response, body){
    var second = JSON.parse(body);

    options.url = 'http://example.com/third' + second.title;

    //another nested request
    request.get(options, function(error, response, body){
      var third = JSON.parse(body);
      return third;
    });
  })
})

Is there a better way to do the chained promised?

The Request library does not support promises directly . You can use request-promise (or request-promise-native if using ES6) to use Promises with request :

// run `npm install request request-promise` first

var request = require('request-promise');

var options = {
  uri: 'http://example.com',
  json: true // Automatically parses the JSON string in the response
};

request.get(options).then(function(body){
  //second request
  options.url = 'http://example.com/second' + body.id;    
  return request.get(options)
}).then(function(body){
  //third request
  options.url = 'http://example.com/third' + body.title;
  return request.get(options)
}).then(function(body){
  return body;
}).catch(function(error){
  // error handling
});

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