0

Hello I have this function:

private _getServiceTask(tasks) {
    let result:;

    tasks.map(async (task, index) => {
      if (index === 0) {
        result = await callApi({
          id: task.provider_id,
        });
        return;
      }

      if (index !== 0 && task.provider_id !== tasks[index - 1].provider_id) {
        result = await callApi({
          id: task.provider_id,
        });
      }

      if (result) {
        const { providers } = result;
        providers?.map((provider) =>
          task.settings?.push({
            name_translations: provider.name_translations,
            description_translations: provider.description_translations,
          })
        );
      }
    });
  }

I would like to assign result a value and keep it until a condition is matched in .map function and result is reassigned to another value.

My issue is that in the first loop, result has value, and then is undefined. Anyone knows what I'm doing wrong?

Simon
  • 209
  • 4
  • 12

1 Answers1

2

Array#map does not handle waiting for async functions. Use a for ... of loop instead and make _getServiceTask async. (Also, don't use map to loop over an array. Use Array#forEach or for loops.)

for (const [index, task] of tasks.entries()) {
  if (index === 0) {
    result = await callApi({
      id: task.provider_id,
    });
  }

  if (index !== 0 && task.provider_id !== tasks[index - 1].provider_id) {
    result = await callApi({
      id: task.provider_id,
    });
  }

  if (result) {
    const { providers } = result;
    providers?.forEach((provider) =>
      task.settings?.push({
        name_translations: provider.name_translations,
        description_translations: provider.description_translations,
      })
    );
  }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thank you for your answer, I have two issues with this function. First one it says that "ESLint: Unexpected `await` inside a loop.(no-await-in-loop)". and the second one says that "Variable 'result' is used before being assigned.". It's weird – Simon Oct 05 '22 at 15:28
  • @Simon You can ignore that first warning. See here: https://stackoverflow.com/questions/48957022/unexpected-await-inside-a-loop-no-await-in-loop – Unmitigated Oct 05 '22 at 15:31
  • @Simon The second warning is probably due to TypeScript not detecting that you are checking `if (result)`. – Unmitigated Oct 05 '22 at 15:32