如何将Array.prototype.filter与async一起使用? [英] How to use Array.prototype.filter with async?

查看:135
本文介绍了如何将Array.prototype.filter与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是一个回调必须返回true或false 的函数. 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/zh-CN/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.

  • 是否可以在过滤器中使用异步功能?
  • 如果没有,我能做的最简单的替换是什么?

推荐答案

没有办法将过滤器与异步功能一起使用(至少我知道). 必须将filter与promises集合一起使用的最简单方法是使用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与async一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆