sách gpt4 ai đã đi

javascript - 等到嵌套的 promise 解决

In lại 作者:行者123 更新时间:2023-11-30 07:51:48 25 4
mua khóa gpt4 Nike

我正在尝试对数据库进行一系列嵌套调用,并希望在结果全部返回后做一些事情。我是新手,所以如果我完全做错了(可能是这样),请原谅我

我的代码目前是这样的:

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)
})

1 Câu trả lời

尝试使用hai Promise.all - 每个video一个,members一个, comments, keywords, Và 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/

25 4 0
Bài viết được đề xuất: javascript - 如何快速通过护照认证
Bài viết được đề xuất: java - GCP 数据流 - 从存储中读取 CSV 文件并写入 BigQuery
Bài viết được đề xuất: javascript - 在方法对象上循环 Pomise
Bài viết được đề xuất: java - 拆分出现 "."的单词
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com