[英]How to make http requests in my case?
我正在嘗試使用 NodeJs 請求模塊鏈接 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;
});
})
})
有沒有更好的方法來實現鏈式承諾?
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.