-1

I have next code:

contents.map((content) => {
    const element = Object.assign({}, content);
    if (element.type === 'blabla') {
      element.data.id = await getId();
    }
    return element;
  });

But it fails with next error:

The 'await' operator can only be used in an 'async' function

Ted
  • 1,682
  • 3
  • 25
  • 52
  • `(content) => {…}` is not an `async` function indeed – Bergi Apr 05 '21 at 12:41
  • A better option would be to replace `map` with a `for of ` loop. – georg Apr 05 '21 at 12:44
  • Does this answer your question? [Use async await with Array.map](https://stackoverflow.com/questions/40140149/use-async-await-with-array-map) – goto Apr 05 '21 at 12:46

2 Answers2

0

Make each map function async and use Promise.all():

await Promise.all(contents.map(async content => ...);

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input's promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Note that this means all content items are processed in parallel. If you want sequential execution, use for ... of instead. Each iteration may await as needed.

JHH
  • 8,567
  • 8
  • 47
  • 91
-1

Just add async in starting of your function.

You cant use await without async.

contents.map(async (content) => {
    const element = Object.assign({}, content);
    if (element.type === 'blabla') {
      element.data.id = await getId();
    }
    return element;
  });

You have to provide whole code for correct result, i just wanted to tell you the mistake you are doing.

Ashishssoni
  • 729
  • 4
  • 14
  • 2
    I don't think "just add async" is the right answer, because they most probably want the whole `map` to be async as well. – georg Apr 05 '21 at 12:44
  • but for that, he needs to provide whole code. Based on his question, its the best way to let him know what he is missing. – Ashishssoni Apr 05 '21 at 12:47