如何正确地同步解析打字稿中的承诺列表 / javascript

How properly synchronous resolve list of promises in typescript / javascript

我有从数据库中获取数据、修改并保存的承诺列表, 一些承诺可以使用相同的数据,以排除可能的冲突,我决定同步执行承诺,我编写下一个函数,但我怀疑它可以更简单地完成和规则。

打字稿

async function syncPromises<T>(arr: (() => Promise<T>)[]) {
  const result : T[] = [];

  for(const fn of arr) {
    result.push(await fn());
  }

  return result;
}

JavaScript

async function syncPromises(arr) {
  const result = [];

  for(const fn of arr) {
    result.push(await fn());
  }

  return result;
}

目前调用函数我使用类似的代码

const ids = [ 3, 5 ];
syncPromises(ids.map(id => () => someLogicWhatNeedExecSync(id)));

我觉得这样可以更简单

不是采用一组函数,而是采用一组值和一个应用于它们的函数 - 基本上 map:

async function sequentialMap<V, R>(arr: V[], fn: (v: V) => Promise<R>): Promise<R[]> {
  const result : R[] = [];
  for (const value of arr) {
    result.push(await fn(value));
  }
  return result;
}

您可以将其用作

const ids = [ 3, 5 ];
sequentialMap(ids, someLogicWhatNeedExecSync);

JavaScript 和 TypeScript 在循环你想要等待的函数时有一些微妙之处。

此页面很好地解释了选项和差异:https://advancedweb.hu/how-to-use-async-functions-with-array-foreach-in-javascript/

如果您希望在 returning 之前解决所有承诺,那么您不能使用 for 循环,而应该使用 arr.map()arr.reduce()

在您想要 return 数组的情况下,最简单的方法可能是使用 arr.map(),因为它 return 是一个数组。

完全同意@Bergi 提到的方法。 另一种方法是使用 Promise.all()

function asyncTimeoutFunction(id){
    return new Promise(resolve=>{
        setTimeout(()=>resolve(id),1000);
    })
}

const ids = [ 3, 5, 2 ];
const functions = ids.map((id)=>{
    return asyncTimeoutFunction(id);
});

Promise.all(functions).then(console.log);

只需将您的异步函数替换为 asyncTimeoutFunction。