我正在尝试对数据库进行一系列嵌套调用,并希望在结果全部返回后做一些事情。我是新手,所以如果我完全做错了(可能是这样),请原谅我
我的代码目前是这样的:
getVideos(user).then((videos) => {
videos.forEach((video) => {
getImage(video).then(() => {
getMembers().then((members) => {
getComments().then((comments) => {
getKeywords().then((keywords) => {
getTranscript().then((transcript) => {
console.log(members, comments, keywords, transcript)
}
}
}
}
})
})
})
这显然非常低效,因为 getMembers()
、getComments()
、getKeywords()
和 getTranscript()
不需要互相等待,都可以异步调用。此外,可以为循环中的每个视频异步调用 getImage()
,无需等待。
我正在尝试更改代码以将这些 promise 捆绑成一个大 promise ,这样一旦它解决,我就可以在一个地方访问所有获取的数据。这是我的尝试,但它打印了
Promise{...}, Promise{...}, Promise{...}, Promise{...}
而不是获取的数据。
知道我做错了什么以及如何正确地将所有这些嵌套的 promise 变成一个吗?谢谢
let members, comments, keywords, transcript
getVideos(user).then((videos) => {
let promises = []
videos.forEach((video) => {
let p = getImage(video).then(() => {
members = getMembers()
comments = getComments()
keywords = getKeywords()
transcript = getTranscript()
return Promise.all([members, comments, keywords, transcript])
})
promises.push(p)
})
return Promise.all(promises)
})
.then(() => {
console.log(members, comments, keywords, transcript)
})
最佳答案
尝试使用两个 Promise.all
- 每个video
一个,members
一个, comments
, keywords
, and transcript
:
getVideos(user).then((videos) => Promise.all(
videos.map(video => getImage(video)
.then(videoResp => Promise.all([
getMembers(), // do you need to call these functions with `videoResp`?
getComments(),
getKeywords(),
getTranscript(),
]))
)
));
promise 链然后会解析成类似的东西
[ [
// video 1
v1members,
v1comments,
v1keywords,
v1transcript,
],
[
// video 2
v2members,
v2comments,
v2keywords,
v2transcript,
],
// ...
]
关于javascript - 等到嵌套的 promise 解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529197/