admin管理员组文章数量:1289583
If I have an array of promises, I can simply use Promise.all
to wait for them all.
But when I have an array of objects, each of them having some properties that are promises, is there a good way to deal with it?
Example:
const files=urlOfFiles.map(url=>({
data: fetch(url).then(r=>r.blob()),
name: url.split('/').pop()
}))
//what to do here to convert each file.data to blob?
//like Promise.all(files,'data') or something else
If I have an array of promises, I can simply use Promise.all
to wait for them all.
But when I have an array of objects, each of them having some properties that are promises, is there a good way to deal with it?
Example:
const files=urlOfFiles.map(url=>({
data: fetch(url).then(r=>r.blob()),
name: url.split('/').pop()
}))
//what to do here to convert each file.data to blob?
//like Promise.all(files,'data') or something else
Share
Improve this question
edited Jan 13, 2018 at 13:20
Ahmad Baktash Hayeri
5,8804 gold badges32 silver badges43 bronze badges
asked Jan 13, 2018 at 13:05
3142 maple3142 maple
9072 gold badges11 silver badges29 bronze badges
3 Answers
Reset to default 10Instead of mapping the data to an array of objects, you could map it to an array of promises that resolve to objects:
const promises = urlOfFiles
.map(url => fetch(url)
// r.blob() returns a promise, so resolve that first.
.then(r => r.blob())
// Wrap object in parentheses to tell the parser that it is an
// object literal rather than a function body.
.then(blob => ({
data: blob,
name: url.split('/').pop()
})))
Promise.all(promises).then(files => /* Use fetched files */)
Try something like this:
const files = urlOfFiles.map(url=>
fetch(url).then(r=> ({
data: r.blob()
name: url.split('/').pop()
})
))
Promise.all(files)
With multiple async properties of the return value you could use nested Promise.all
(if other async results rely on response of fetch
) or as Tulir suggested; start off with a Promise.all([fetch(url),other])...
:
Promise.all(
urlOfFiles.map(
url=>
fetch(url)
.then(
r=>
Promise.all([//return multiple async and sync results
r.blob(),
Promise.resolve("Other async"),
url.split('/').pop()
])
)
.then(
([data,other,name])=>({//return the object
data,
other,
name
})
)
)
)
.then(
files=>
console.log("files:",files)
);
本文标签:
版权声明:本文标题:javascript - Is there a good way to Promise.all an array of objects which has a property as promise? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741430635a2378338.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论