如何将 Array.prototype.filter 与异步一起使用? [英] How to use Array.prototype.filter with async?
问题描述
我正在尝试过滤一组对象.在过滤之前,我需要将它们转换为某种格式,并且此操作是异步的.
I am trying to filter an array of objects. Before I filter, I need to convert them to some format, and this operation is asynchronous.
const convert = () => new Promise( resolve => {
setTimeout( resolve, 1000 );
});
因此,我的第一次尝试是使用 async/await 执行以下操作:
So, my first try was to do something like the following using async/await:
const objs = [ { id: 1, data: "hello" }, { id: 2, data: "world"} ];
objs.filter( async ( obj ) => {
await convert();
return obj.data === "hello";
});
现在,正如你们中的一些人可能知道的那样,Array.protoype.filter
是一个回调函数必须返回真或假.filter
是同步的.在前面的例子中,我没有返回它们,我返回一个 Promise (所有异步函数都是 Promises ).
Now, as some of you may know, Array.protoype.filter
is a function which callback must return either true or false. filter
is synchronous. In the previous example, I am returning none of them, I return a Promise ( all async functions are Promises ).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
因此可以假设,之前的代码并没有真正起作用......这个假设是正确的.
So as one can assume, the code before doesn't really work... That assumption is correct.
为了使过滤器与异步函数一起工作,我检查了 stackoverflow 并找到了这个主题:
To make filter work with an async function, I checked stackoverflow and found this topic:
不幸的是,选择的答案过于复杂并且使用了类.这对我不起作用.相反,我正在寻找一个更简单的解决方案,使用简单的函数和函数式方法.
Unfortunately, the chosen answer is overly complex and uses classes. This won't do for me. I am instead looking for a more simple solution, using simple functions with a functional approach.
最后有一个解决方案,使用带有回调的地图来模拟过滤器:
There is one solution at the very end, using a map with a callback to simulate a filter:
https://stackoverflow.com/a/46842181/1337392
但我希望修复我的过滤器功能,而不是替换它.
But I was hoping to fix my filter function, not to replace it.
- 有没有办法在过滤器中使用异步函数?
- 如果没有,我能做的最简单的替换是什么?
推荐答案
没有办法将过滤器与异步函数一起使用(至少我知道).对 promise 集合使用 filter 的最简单方法是使用 Promise.all
然后将该函数应用于结果集合.它看起来像这样:
There is no way to use filter with an async function (at least that I know of).
The simplest way that you have to use filter with a collection of promises is to use Promise.all
and then apply the function to your collection of results.
It would look something like this:
const results = await Promise.all(your_promises)
const filtered_results = results.filter(res => //do your filtering here)
希望有帮助.
这篇关于如何将 Array.prototype.filter 与异步一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!