链多节点http请求 [英] Chain multiple Node http request
问题描述
我是节点新手,需要从我的代码中调用第三方API。我通过使用此链接中的http.request找到了如何执行此操作 https://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request 。我需要做的是调用两个不同的api url并使用第二次调用中第一次调用的响应数据,这将只是一个id作为resource2上的参数。
I am new to node and need to call a 3rd party api from my code. I found how to do this by using http.request from this link https://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request. What I need to do is call two different api urls and use the response data from the first call in the second call which will just be an id as a param on resource2.
我不知道如何将这两个调用链接在一起而不会是一个重复的混乱。任何帮助将不胜感激。
I do not know how I would chain two of these calls together without it being a duplicated mess. Any help would be appreciated.
var url1 = {
host: 'www.domain.com',
path: '/api/resourse1'
};
var url2 = {
host: 'www.domain.com',
path: '/api/resourse2/{id}'
};
var callback = function (response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
http.request(url1, callback).end();
推荐答案
首先,你要看看请求,由于其简单性,这是HTTP请求最受欢迎的选择。
Firstly, you'll want to take a look at request, which is most popular choice for HTTP requests, due to its simplicity.
其次,我们可以将请求的简单性与Promises的概念结合起来,连续发出多个请求,同时保持代码平稳。
使用请求承诺
Secondly, we can combine the simplicity of request with the concept of Promises, to make multiple requests in succession, while keeping the code flat.
Using request-promise
var rp = require('request-promise')
var url1 = {}
var url2 = {}
var url3 = {}
rp(url1)
.then(response => {
// add stuff from url1 response to url2
return rp(url2)
})
.then(response => {
// add stuff from url2 response to url3
return rp(url3)
})
.then(response => {
// do stuff after all requests
// If something went wrong
// throw new Error('messed up')
})
.catch(err => console.log) // Don't forget to catch errors
如您所见,我们可以根据需要添加任意数量的请求,以及代码w生病扁平而简单。作为奖励,我们也能够添加错误处理。使用传统的回调,你必须为每个回调添加错误处理,而在这里我们只需要在Promise链的末尾执行一次。
As you can see, we can add as many requests as we want, and the code will stay flat and simple. As a bonus, we were able to add error-handling as well. Using traditional callbacks, you'd have to add error-handling to every callback, whereas here we only have to do it once at the end of the Promise chain.
更新(09/16):虽然Promise将我们带到了中途,但进一步的经验使我确信Promise独自会变得混乱同步,异步代码,尤其是控制流(例如if-else)之间的混合很多。解决这个问题的规范方法是 async /等待,但仍在开发中,需要翻译。因此,生成器是下一个最佳解决方案。
UPDATE (09/16): While Promises take us halfway there, further experience has convinced me that Promises alone get messy when there is a lot of mixing between sync, async code, and especially control flow (e.g. if-else). The canonical way to solve this would be with async/await, however that is still in development and would require transpilation. As such, generators are the next best solution.
使用 co </a>
Using co
var co = require('co')
var rp = require('request-promise')
var url1 = {}
var url2 = {}
var url3 = {}
co(function* () {
var response
response = yield rp(url1)
// add stuff from url1 response to url2
response = yield rp(url2)
// add stuff from url2 response to url3
response = yield rp(url3)
// do stuff after all requests
// If something went wrong
// throw new Error('messed up')
})
.catch(err => console.log) // Don't forget to catch errors
UPDATE(12/16):现在编写时的最新版本节点(7.2.1)支持后面的async / await - 和谐
flag,你可以这样做:
UPDATE (12/16): Now that the latest version of node at time of writing (7.2.1) supports async/await behind the --harmony
flag, you could do this:
const rp = require('request-promise')
const url1 = {}
const url2 = {}
const url3 = {}
async function doRequests() {
let response
response = await rp(url1)
// add stuff from url1 response to url2
response = await rp(url2)
// add stuff from url2 response to url3
response = await rp(url3)
// do stuff after all requests
// If something went wrong
// throw new Error('messed up')
}
doRequests()
.catch(err => console.log) // Don't forget to catch errors
这篇关于链多节点http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!