gpt4 book ai didi

javascript - 在 Promise 中返回 Promise 的值

转载 作者:行者123 更新时间:2023-12-03 02:28:19 25 4
gpt4 key购买 nike

我有一些 promise 需要在函数返回之前完成。我有一个可以检索个人资料的 promise 。如果配置文件的类型为 artist 我想使用该配置文件上的 itunesId 属性获取一些 json 数据,那么我想从 Promise 返回并访问两个配置文件值和 json 数据。如果配置文件的类型为 fan,那么在检索配置文件后,它应该只返回该配置文件。

我正在尝试这样的事情,但我知道这是错误的,我只是不知道如何让它发挥作用。目前,当我打印 music 时,它说它未定义。我知道 getiTunesMusic 函数确实正确返回对象数组。

var promises = []
var profilePromise = userRef.get().then(doc => {
if (doc.exists) {
var profile = doc.data()
profile.id = doc.id

if (type === UserType.artist) {
if (profile.hasOwnProperty("itunesId")) {
return [profile, getiTunesMusic(profile.itunesId)]
} else {
return profile
}
} else {
return profile
}
} else {
throw new Error("Profile doesn't exist")
}
})


promises.push(profilePromise)

// Later on
Promise.all(promises)
.then(objects => {
var profile = objects[0]
var music = objects[1]
console.log(music) // Undefined
})

最佳答案

据我所知,getiTunesMusic(id) 返回一个 Promise。因此,本例中的结果是一个如下所示的数组:[profile, Promise]

你需要的是像这样链接你内心的 promise :

return getiTunesMusic(profile.itunesId).then(music => [profile, music]);

从传递给 next 的回调中返回 Promise 会产生一个 Promise,该 Promise 仅当两个 Promise 都解析时才解析,并且其结果是内部 Promise 的结果。在本例中,[个人资料,音乐] 就是您想要的。

关于javascript - 在 Promise 中返回 Promise 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48846672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com