匹配的网址异步请求的针的NodeJS处理阵列目标:用的StatusCode
鉴于URL的数组,我需要发送一个请求,并取回的StatusCode为每一个。最后,我需要将statusCode与一个对象数组中的请求URL进行匹配,然后将其返回到页面。
像这样:
checkList: [
{
name: "Google",
url: "https://www.google.com"
},
{
name: "Microsoft",
url: "https://www.microsoft.com"
},
{
name: "Github",
url: "https://www.github.com"
}
]
对于列表中的每个URL,我需要简单地使一个HTTP请求并返回一个状态代码(例如:200),并匹配以请求路径。所以最终的输出应该是这样的......
results: [
{
name: "Google",
url: "https://www.google.com",
status: 200
},
{
name: "Microsoft",
url: "https://www.microsoft.com",
status: 200
},
{
name: "Github",
url: "https://www.github.com",
status: 200
}
]
我目前使用BluebirdJS和Needle处理异步调用获得响应代码。
问题是我看不到一种方法来匹配请求URL和响应。由于每个结果都会在不同的时间返回(如预期的那样),并且Needle响应中不包含请求URL,所以我不能说类似......“https://google.com响应为200”。我只能得到一个响应代码列表。
我对高级JS比较新,所以也许有一种方法可以覆盖回调/承诺,它允许我通过整个过程传递请求URL,但我不知道如何。
这是我目前使用的基于演示/段我发现其他地方的代码的要点... https://gist.github.com/sgelliott/13840b6f2f9d2ab481fcded6dc4a9188
代码还包括如下内联...
var needle = require('needle');
var Promise = require("bluebird");
Promise.promisifyAll(needle);
var allPaths = ["https://google.com", "https://microsoft.com", "https://github.com"];
var current = Promise.resolve();
Promise.map(allPaths, function(path) {
current = current.then(function() {
console.log("path: " + path); // path shows up here correctly - it's available
return needle.getAsync(path, options);
});
return current;
}).map(function(resp, body) {
return {
path: "path goes here",
status: resp.statusCode
};
}).then(function(results) {
console.log("results: " + JSON.stringify(results)); // this outputs 'resulst' : [{"path":"path goes here","status":200},{"path":"path goes here","status":302},{"path":"path goes here","status":200}]
return renderResults(results); //this simply sets 'statusResults' to 'results' for the next res.send to use - will refine once I solve the path matching issue
}).then(function() {
console.log('All Needle requests are processed!');
res.send(statusResults); //
}).catch(function(e) {
console.log(e);
});
如果这是其他事情的重复,我表示歉意。经过大量研究后,我无法找到它。如果解决方案是使用Needle以外的东西,那很好。我宁愿坚持使用蓝鸟。先谢谢你!
为什么不把代码放在问题本身,而不是外部链接将过时,然后这个问题是没有用的未来的读者? –
在第20行...你在哪里说'我无法访问原始请求URL /路径以匹配'...结果[n]不会是'allPaths [n]的结果' –
@JaromandaX我从未打算摧毁Gist,但我已经调整了帖子以将其包含在内。至于你的问题......这是一个很好的问题。我假设,由于异步调用可能会在给定网络流量的不同时间返回值,因此不能保证结果数组的顺序与原始请求URL集的顺序相同。你知道这样的事情是否有保证吗?看起来有更合适的方法来做到这一点。 – sgelliott