我正在尝试使用NodeJs Request模块链接http请求。
示例:
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;
});
})
})
有没有更好的方法来做链接承诺?
答案 0 :(得分:1)
请求库does not support promises directly。您可以使用request-promise
(或request-promise-native
,如果使用ES6)将Promises与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
});