在Array.find()中使用异步函数 [英] Using an async function in Array.find()

查看:77
本文介绍了在Array.find()中使用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎我无法使用异步函数作为Array.find()的第一个参数.我看不出为什么这段代码无法正常运行?

It seems I'm unable to use an async function as the first argument to Array.find(). I can't see why this code would not work what is happening under the hood?


function returnsPromise() {
  return new Promise(resolve => resolve("done"));
}

async function findThing() {
  const promiseReturn = await returnsPromise();
  return promiseReturn;
}

async function run() {
  const arr = [1, 2];
  const found = await arr.find(async thing => {
    const ret = await findThing();
    console.log("runs once", thing);
    return false;
  });
  console.log("doesn't wait");
}

run();

https://codesandbox.io/s/zk8ny3ol03

推荐答案

简单地说, find 不会期望返回承诺,因为它不是用于异步事物的.它循环遍历数组,直到其中一个元素导致返回真实值.一个对象(包括一个promise对象)是真实的,因此查找在第一个元素上停止.

Simply put, find does not expect a promise to be returned, because it is not intended for asynchronous things. It loops through the array until one of the elements results in a truthy value being returned. An object, including a promise object, is truthy, and so the find stops on the first element.

如果您想要异步等效的find,则需要自己编写.您需要考虑的一个问题是,是要并行运行事物,还是要顺序运行事物,在进入下一个索引之前会阻塞.

If you want an asynchronous equivalent of find, you'll need to write it yourself. One consideration you'll want to have is whether you want to run things in parallel, or if you want to run them sequentially, blocking before you move on to the next index.

例如,这是一个并行运行它们的版本,然后,所有的诺言都得到解决后,它会找到第一个产生真实值的人.

For example, here's a version that runs them all in parallel, and then once the promises are all resolved, it finds the first that yielded a truthy value.

async function findAsync(arr, asyncCallback) {
  const promises = arr.map(asyncCallback);
  const results = await Promise.all(promises);
  const index = results.findIndex(result => result);
  return arr[index];
}

//... to be used like:

findAsync(arr, async (thing) => {
  const ret = await findThing();
  return false;
})

这篇关于在Array.find()中使用异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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