Search code examples
javascripttypescriptes6-promise

How properly synchronous resolve list of promises in typescript / javascript


I have list of promises what obtain data from database, modify it and save, some promises can work with same data, to exclude possible conflicts, I decide execute promise synchronous, I write next function, but I suspect that it can be done more simply and the rule.

Typescript

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;
}

Currently I use similar code for call function

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

I think this can be more simple


Solution

  • Instead of taking an array of functions, take an array of values and a single function to apply to them - basically 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;
    }
    

    You can use it as

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