简体   繁体   English

异步数组。map 返回未定义

[英]Async array.map returning undefined

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.我不太明白为什么我的异步 map fetch function 无论我做什么都会返回一个未定义值的数组或“Promise {}”。 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?我的 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)

You need to change你需要改变

await fetch(book.imageURL)

to

return fetch(book.imageURL)

in the getImageRef() function.getImageRef() function 中。

That way, docs will be equal to whatever getImageRef() returns.这样, docs将等于getImageRef()返回的任何内容。 It's required because await itself does not cause the whole getImageRef() function to return anything.这是必需的,因为await本身不会导致整个getImageRef() function 返回任何内容。 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. function 返回return关键字之后的任何内容,如果未提供,则返回undefined - 这就是您的情况下undefined的来源。

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

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