[英]Nested API requests in a route node/express
我对编码非常陌生,这是我在这里的第一篇文章。 我的学习项目是一个网站,该网站使用外部CRM来存储来自Web表单的客户数据。
我的存储部分工作正常,但无法弄清楚如何检索数据并将其传递给呈现的页面。 我需要一条路线来执行3个操作,每个操作本身都能正常工作,我只是想不出如何嵌套它们以便它们按顺序发生。
var options = { method: 'GET',
url: 'https://crm.com/dev/api/opportunity/' + req.params.id,
headers:
{ 'cache-control': 'no-cache',
'content-type': 'application/json',
accept: 'application/json',
authorization: 'Basic xxx' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
return body.contact_ids;
});
这将返回与交易相关的客户编号数组。
遍历客户端编号以从每个客户端中查找数据,并将其放入数组。 我在函数范围之外定义了一个名为data的空数组以捕获结果。
resultFromAboveRequest.forEach(function(id) { var options = { method: 'GET', url: 'https://crm.com/dev/api/contacts/' + Number(id), headers: { 'cache-control': 'no-cache', 'content-type': 'application/json', accept: 'application/json', authorization: 'Basicxxx' }, json: true }; request(options, function (error, response, body) { if (error) throw new Error(error); data.push(body); }); });
将结果数据数组呈现在页面上
res.render("./applicants/resume", {data: data});
我很确定这是对Promise的工作,但是我似乎无法理解语法。 任何帮助将不胜感激,如果这个问题的格式是业余的或以某种方式不适当,我深表歉意。
我建议使用request-promise
库(这是request
库的Promise接口),然后使用Promise在一系列异步操作中管理排序和错误处理。 您可以这样做:
const rp = require('request-promise');
const options = {
method: 'GET',
url: 'https://crm.com/dev/api/opportunity/' + req.params.id,
headers: {
'cache-control': 'no-cache',
'content-type': 'application/json',
accept: 'application/json',
authorization: 'Basic xxx'
},
json: true
};
rp(options).then(body => {
return Promise.all(body.contact_ids.map(id => {
const options = {
method: 'GET',
url: 'https://crm.com/dev/api/contacts/' + Number(id),
headers: {
'cache-control': 'no-cache',
'content-type': 'application/json',
accept: 'application/json',
authorization: 'Basicxxx'
},
json: true
};
return rp(options);
}));
}).then(data => {
res.render("./applicants/resume", {data: data})
}).catch(err => {
console.log(err);
res.status(500).send("internal server error");
});
以下是步骤的一般说明:
.then()
处理函数以获取结果。 .map()
处理结果。 .map()
回调中,从对每个数据项的请求承诺的调用中返回另一个诺言。 这意味着.map()
将返回一个promise数组。 Promise.all()
数组上使用Promise.all()
可以知道何时完成。 Promise.all()
返回Promise.all()
以便将其链接到先前的.then()
处理程序进行排序。 .then()
处理函数中(直到之前的两个操作都完成后才会调用),您将以适当的顺序从.map()
操作中获取数据,可用于调用res.render()
。 .catch()
来捕获.catch()
链中的任何错误(所有错误都将传播到此.catch()
,您可以在其中发送错误响应)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.