1

Here is my code. Can't figure out why the error occured. The function is async type.

const func = async () => {
      {submission[0].emoticons.map((item, idx) => {
        console.log('apngToFrame is working')
        const imgsrc = `${url}${item.id}`
        var container2 = document.querySelector('.output2')
        const response = await fetch(imgsrc)
        const buffer = await response.arrayBuffer()
        const apng = parseAPNG(buffer)
        if (apng instanceof Error){
          console.error('apng.message', apng.message)
          return ;
        }
        await apng.createImages()
        apng.frames.forEach(f => {
          container2.appendChild(f.imageElement)
        })
      })}
    }
mk23
  • 1,257
  • 1
  • 12
  • 25
angie
  • 59
  • 5
  • 4
    The function that those lines are inside is the one starting with this: `(item, idx) => {` . That is not an async function. – Nicholas Tower Jul 28 '21 at 04:33
  • `await` is only valid in async function. the callback to your `emoticons.map` method is not `async`. change this to `async (item, idx)` – Amir Saleem Jul 28 '21 at 04:36
  • 1
    Why are you using `map`? You’re not using its result and don’t return anything. Use `forEach` instead. – Sebastian Simon Jul 28 '21 at 04:37
  • Does this answer your question? [JavaScript async/await for Promises inside Array.map()](https://stackoverflow.com/questions/38694958/javascript-async-await-for-promises-inside-array-map) – Sebastian Simon Jul 28 '21 at 04:38
  • 1
    The await is not inside an `async` function. Check it out: `.emoticons.map((item, idx) => {` There is no `async` keyword in the function you are using `await` in – slebetman Jul 28 '21 at 04:52
  • 1
    @SebastianSimon For this specific use-case he shouldn't even be using `forEach` since it will still be problematic because it is a function. He needs to use either a `for` or `while` loop and no a function – slebetman Jul 28 '21 at 04:53

1 Answers1

0

Add async for the callback function that you are using in the map

const func = async () => {
      {submission[0].emoticons.map(async(item, idx) => {
        console.log('apngToFrame is working')
        const imgsrc = `${url}${item.id}`
        var container2 = document.querySelector('.output2')
        const response = await fetch(imgsrc)
        const buffer = await response.arrayBuffer()
        const apng = parseAPNG(buffer)
        if (apng instanceof Error){
          console.error('apng.message', apng.message)
          return ;
        }
        await apng.createImages()
        apng.frames.forEach(f => {
          container2.appendChild(f.imageElement)
        })
      })}
    }
sanket naik
  • 378
  • 3
  • 7