[英]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.