[英]How to make http requests in my case?
I am trying to chain the http requests using NodeJs Request modules.我正在尝试使用 NodeJs 请求模块链接 http 请求。
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 . Request 库不直接支持承诺。 You can use request-promise
(or request-promise-native
if using ES6) to use Promises with request
:您可以使用request-promise
(如果使用 ES6,则使用request-promise-native
)将 Promise 与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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.