0

I can't quite work out why my async map fetch function returns an array of undefined values or "Promise { }" no matter what I do. My getImageRef function works (I've tried to simplify it by stripping some bits out) but how do I get it to return values to the Promise.all in formatBooks?

const inventory = [
    {
    "isbn":"foo",
    "title":"bar",
    "imageURL":"http://web.com/image.jpg"
    }
]
const getImageRef = async book => { //this part works on its own
  await fetch(book.imageURL)  
    .then(res => res.buffer())
    .then(buffer => client.assets.upload('image', buffer))
    .then(assetDocument => {
      let book.imageRef = assetDocument._id
      return book
    })
    .catch(() => {
      console.error('Error: ' + book.image)
      return book
    })
  }

async function formatBooks (inventory) {

  await Promise.all(inventory.map(async book => {
        const docs = await getImageRef(book) // 'docs' returns as undefined

      })
  ).then(function(docs) {   
    uploadBooks(docs)
  })
}
function uploadBooks (documents) {   
  console.log(documents)
}
formatBooks(data)
j-adom
  • 1
  • Your `.map` callback doesn't return anything, so your `inventory.map` call just produces an array of promises that all resolve to `undefoned`. – VLAZ May 19 '20 at 05:30
  • you need to return the promises or awaited(resolved) values, also use `await` or `.then` chains. – AZ_ May 19 '20 at 05:35
  • Try changing `await fetch(book.imageURL)` to `return fetch(book.imageURL)` in the `getImageRef()` function. That way, `docs` should be equal to whatever `getImageRef()` returns – Sebastian Kaczmarek May 19 '20 at 05:40
  • 1
    @SebastianKaczmarek wow that got it working! I have been looking all over and haven't come across that syntax before. Thanks! – j-adom May 19 '20 at 07:05
  • Glad I could help. Posted as an answer ;) – Sebastian Kaczmarek May 19 '20 at 07:25

1 Answers1

0

You need to change

await fetch(book.imageURL)

to

return fetch(book.imageURL)

in the getImageRef() function.

That way, docs will be equal to whatever getImageRef() returns. It's required because await itself does not cause the whole getImageRef() function to return anything. The function returns whatever comes after the return keyword or undefined if it's not provided - and that's where the undefined comes from in your case.

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38