【发布时间】:2017-11-18 01:20:01
【问题描述】:
我正在尝试了解 Promise API。
测试用例: 我正在使用来自jsonplaceholder 的三个API。
/user/{userId} #Returns a user
/posts?userId=1 #Returs list of posts by user
/comments?postId=1 #Returns list of comments for the post
我需要将所有三个 API 的输出组合成如下结构。
var user = {
'id' : "1",
"name" : "Qwerty",
"posts" : [
{
"id" : 1,
"userid" : 1,
"message" : "Hello",
"comments" : [
{
'id' : 1,
"postId" :1
"userid" : 2,
"message" : "Hi!"
},
{
'id' : 2,
"postId" :1
"userid" : 1,
"message" : "Lets meet at 7!"
}
]
}
]
}
我面临的挑战是将 cmets 合并到每个帖子。请帮忙。我的意思是我不确定该怎么做。
当前实施。
var xyz = function (userId) {
return Promise.all(
[
usersApi.getUsersByIdPromise(userId),
postsApi.getPostsForUserPromise(userId)
]
).spread((user, posts) => {
user.posts = posts;
for (let post of user.posts){
commentsApi.getCommentsForPostPromise(post.id)
.then(comments => {
//Merge comments to post
//How do i return a merged user object
});
}
})
}
【问题讨论】:
-
您尝试对
Promise.all的结果使用的spread方法是什么?标准 Promise API 中没有spread。 -
它的bluebirdjs.com,请在标准promise API中给出解决方案。
标签: javascript promise bluebird es6-promise