requestpromise循环,如何包含随响应一起发送的请求数据



我试图在循环中使用请求承诺,然后将一个包含所有响应的响应发送回客户端。下面的代码是有效的,但是我也想在每个响应中包含请求数据,这样请求ID就可以与结果相关联。有没有一种内置的方法可以做到这一点:

promiseLoop: function (req, res) {
var ps = [];
for (var i = 0; i < 3; i++) {
// var read_match_details = {
//     uri: 'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
//     json: true // Automatically parses the JSON string in the response 
// };
var session = this.sessionInit(req, res);
if (this.isValidRequest(session)) {
var assertion = session.assertions[i];
const options = {
method: 'POST',
uri: mConfig.serviceURL,
body: assertion,
headers: {
'User-Agent': 'aggregator-service'
},
json: true
}
logger.trace(options);
ps.push(httpClient(options));
}
}
Promise.all(ps)
.then((results) => {
console.log(results); // Result of all resolve as an array
res.status(200);
res.send(results);
res.end();
}).catch(err => console.log(err));  // First rejected promise
}

假设httpClient()是您所引用的request-promise,并且assertion值是您试图通过此结果传递的值,则可以更改此值:

ps.push(httpClient(options));

到此:

ps.push(httpClient(options).then(result => {
return {id: assertion, result};
}));

然后,您的promise将解析为包含结果和id的对象,并且您可以访问最终结果数组中的每一个。


您的代码不显示当前结果。如果它已经是一个对象,如果您愿意,也可以将id属性添加到该对象中。这取决于你如何把最终结果组合在一起。

ps.push(httpClient(options).then(result => {
// add id into final result
result.id = assertion;
return result;
}));

总之,一般的想法是,在将promise放入数组之前,您使用.then()处理程序稍微修改返回的结果,添加您想要添加的任何数据,然后返回新的修改结果,使其成为promise链的解析值。


为了确保处理所有响应,即使有些响应有错误,您也可以使用较新的[Promise.allSettled()][1]而不是Promise.all(),然后查看哪些响应在处理结果时成功或失败。或者,您可以捕捉任何错误,将其转化为已解决的承诺,但给它们一个在处理最终结果时可以看到的重要值(通常为null(:

ps.push(httpClient(options).then(result => {
// add id into final result
result.id = assertion;
return result;
}).catch(err => {
console.log(err);
// got an error, but don't want Promise.all() to stop
// so turn the rejected promise into a resolved promise
// that resolves to an object with an error in it
// Processing code can look for an `.err` property.
return {err: err};
}));

然后,稍后在您的处理代码中:

Promise.all(ps)
.then((results) => {
console.log(results); // Result of all resolve as an array
// filter out error responses
let successResults = results.filter(item => !item.err);
res.send(successResults );
}).catch(err => console.log(err));  // First rejected promise

Promise.allSettled不会在出现错误时停止。它确保你处理所有的回复,即使有些回复有错误。

const request = require('request-promise');
const urls = ["http://", "http://"];
const promises = urls.map(url => request(url));
Promise.allSettled(promises)
.then((data) => {
// data = [promise1,promise2]
})
.catch((err) => {
console.log(JSON.stringify(err, null, 4));
});

最新更新