【发布时间】: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