【发布时间】:2018-01-26 15:13:50
【问题描述】:
如何通过维护异步/并发流程和结果格式以更易读的方式编写以下代码。
var getUsers = () => axios.get("URL").then(res => res.data);
var getPosts = id => axios.get("URL").then(res => res.data);
var getComments = id => axios.get("URL").then(res => res.data);
Promise.map(getUsers(), user => {
return getPosts(user.id).then(posts => {
return Promise.map(posts, post => {
return getComments(post.id).then(comments => {
post["comments"] = comments;
user["posts"] = posts;
return user;
});
});
});
})
.then(res => console.log(JSON.stringify(res)))
.catch(err => console.log(err));
示例格式:
[
{
id:''
name:'..',
email:'',
phone:''
posts:[
{
postId:'...',
title:'....'
body:'....'
comments: [{body:'....'},{body:'...'}]},
{
postId:'...',
title:'....'
body:'....'
comments: [{body:'....'},{body:'...'}]
}
]
}
]
除了下面的 getUsers() 之外的每个 api 都依赖于某些 args 的先前 api。 我正在使用蓝鸟承诺库。 Node Js 版本:v9.3.0
已编辑:我也尝试过类似但使用 3 Promise.map:
var getPosts = id => axios.get("URL").then(res => res.data).then(posts => {
user["posts"] = posts;
return user;
});
var getComments = user => {
return Promise.map(user.posts, post => {
return axios.get(URL).then(res => res.data).then(comments => {
post["comments"] = comments;
return user;
}).then(users => users[0]);
getUsers()
.then(users => Promise.map(users, getPosts))
.then(users => Promise.map(users, getComments))
.then(res => console.log(JSON.stringify(res)))
.catch(err => console.log(err));
【问题讨论】:
-
嵌套提供了闭包。闭包在这里非常有用。建议你坚持你所拥有的。它不是特别难读。
-
user.posts = posts可以移出一层。