I'm trying to sanitize inputs for an asynchronous function. Specifically, given a list of credentials for an API, I'm trying to filter out which ones are invalid by sending a test request to the API and examining the result for each one.
我正在尝试清理异步函数的输入。具体来说,给定一个API的凭证列表,我试图通过向API发送测试请求并检查每个API的结果来过滤掉哪些无效。
The problem I'm facing is this: I would like to collect the invalid keys into a single list. I would normally use the async
library to execute the requests in sequence, using the series
function. But, from the documentation:
我面临的问题是:我想将无效密钥收集到一个列表中。我通常会使用异步库来使用系列函数按顺序执行请求。但是,从文档:
If any functions in the series pass an error to its callback, no more functions are run, and
callback
is immediately called with the value of the error.如果系列中的任何函数将错误传递给其回调,则不再运行任何函数,并立即使用错误值调用回调。
This isn't the desired behavior: I want to collect the errors in place of the responses (or both of them). Is this possible, using this library, without changing the way I'm interacting with the API?
这不是理想的行为:我想收集错误代替响应(或两者)。这是可能的,使用这个库,而不改变我与API交互的方式?
1 个解决方案
#1
2
The solution to this problem ended up being sort of hacky, but it works fine. I had a list of credentials
and an async function apiCall
, which looked like this:
这个问题的解决方案最终变成了一种hacky,但它运行正常。我有一个凭证列表和一个异步函数apiCall,看起来像这样:
var apiCall = function(arg, callback){
...
}
and the solution was to use mapSeries
from async
, but flip the callback arguments, like this:
解决方案是使用async中的mapSeries,但是翻转回调参数,如下所示:
async.mapSeries(credentials, function(creds, callback){
apiCall(creds, function(err, res){
callback(null, err);
});
},
function(nil, errors){
console.log(_.compact(errors));
});
where _.compact
removes falsy elements from the array, getting rid of the null
s that non-error responses returned. This got me exactly what I was looking for.
其中_.compact从数组中删除了falsy元素,去除了非错误响应返回的空值。这让我正是我想要的。
#1
2
The solution to this problem ended up being sort of hacky, but it works fine. I had a list of credentials
and an async function apiCall
, which looked like this:
这个问题的解决方案最终变成了一种hacky,但它运行正常。我有一个凭证列表和一个异步函数apiCall,看起来像这样:
var apiCall = function(arg, callback){
...
}
and the solution was to use mapSeries
from async
, but flip the callback arguments, like this:
解决方案是使用async中的mapSeries,但是翻转回调参数,如下所示:
async.mapSeries(credentials, function(creds, callback){
apiCall(creds, function(err, res){
callback(null, err);
});
},
function(nil, errors){
console.log(_.compact(errors));
});
where _.compact
removes falsy elements from the array, getting rid of the null
s that non-error responses returned. This got me exactly what I was looking for.
其中_.compact从数组中删除了falsy元素,去除了非错误响应返回的空值。这让我正是我想要的。