【问题标题】:Async array.map returning undefined异步 array.map 返回未定义
【发布时间】:2020-09-05 02:14:59
【问题描述】:

无论我做什么,我都无法完全弄清楚为什么我的异步映射获取函数返回一个未定义值的数组或“Promise { }”。我的 getImageRef 函数有效(我试图通过删除一些位来简化它)但是如何让它在 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)

【问题讨论】:

  • 您的 .map 回调不会返回任何内容,因此您的 inventory.map 调用只会生成一组全部解析为 undefoned 的 Promise。
  • 你需要返回promise或者awaited(resolved)的值,也可以使用await或者.then链。
  • 尝试在getImageRef() 函数中将await fetch(book.imageURL) 更改为return fetch(book.imageURL)。这样,docs 应该等于 getImageRef() 返回的任何值
  • @SebastianKaczmarek 哇,它成功了!我一直在寻找,以前没有遇到过这种语法。谢谢!
  • 很高兴我能帮上忙。作为答案发布;)

标签: javascript asynchronous array.prototype.map node-fetch


【解决方案1】:

你需要改变

await fetch(book.imageURL)

return fetch(book.imageURL)

getImageRef() 函数中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 2018-09-22
    • 2016-05-07
    • 1970-01-01
    相关资源
    最近更新 更多