2
const displaySymbols = async (symbols) => {
  const sym = await Promise.all(symbols.map(s => {
    // createEl return a promise
    return createEl(s)
  }))
  return sym
}

const displaySymbols = async (symbols) => {
  const sym = await Promise.all(symbols.map(async s => {
    return await createEl(s)
  }))
  return sym
}

The results are same, without Promise.all, sym would be always a promise array, no matter createEl is await-ed or not, then is it necessary to use async function as map method?

P.S. The code is just a demo.

sfy
  • 2,810
  • 1
  • 20
  • 22
  • No, it's not necessary to use `async`/`await` syntax in the map function, but when your function does something asynchronous that should be waited for it needs to return a promise. – Bergi Nov 26 '17 at 18:23
  • 1
    @Bergi, I didn't get it, in the map function,createEl does things asynchrously, – sfy Nov 26 '17 at 18:30
  • 1
    And `createEl()` does return a promise - so you should `return` that promise. You don't need `async`/`await` for anything. – Bergi Nov 26 '17 at 18:31
  • @Bergi, Thanks, I just saw some other people's code like the second function,that makes me confused. – sfy Nov 26 '17 at 18:35
  • 1
    Those are the people without a clue :-) And of course it could be further simplified to `function displaySymbols(symbols) { return Promise.all(symbols.map(createEl)); }` – Bergi Nov 26 '17 at 18:45

1 Answers1

1

The second one is superflous. Its like:

Promise.resolve( new Promise() )
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151