繁体   English   中英

异步数组。map 返回未定义

[英]Async array.map returning undefined

我不太明白为什么我的异步 map fetch function 无论我做什么都会返回一个未定义值的数组或“Promise {}”。 我的 getImageRef function 工作(我试图通过剥离一些位来简化它)但是我如何让它返回值到 formatBooks 中的 Promise.all ?

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)

你需要改变

await fetch(book.imageURL)

return fetch(book.imageURL)

getImageRef() function 中。

这样, docs将等于getImageRef()返回的任何内容。 这是必需的,因为await本身不会导致整个getImageRef() function 返回任何内容。 function 返回return关键字之后的任何内容,如果未提供,则返回undefined - 这就是您的情况下undefined的来源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM