Skip to content

Commit

Permalink
Refactor and optimize list() (#139)
Browse files Browse the repository at this point in the history
1) Use `ES6` syntax to rewrite `readMessages`/`unreadMessages` instead
of using index for a whole array.
2) Use Promise.all to wrap the mapping from read/unread messages and do
Promise.all to await to save time.
  • Loading branch information
Maledong authored and JacksonTian committed Aug 20, 2018
1 parent e634a68 commit b088d30
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions app/controller/api/message.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,18 @@ class MessageController extends Controller {
const userId = ctx.request.user._id;
const msgService = ctx.service.message;
const mdrender = ctx.request.query.mdrender !== 'false';
const messages = await Promise.all([

// Use ES6 `deconstructor` to analyse the read/unread messages
const [ readMessages, unreadMessages ] = await Promise.all([
msgService.getReadMessagesByUserId(userId),
msgService.getUnreadMessagesByUserId(userId),
]);

let hasReadMessages = await Promise.all(messages[0].map(async message => await msgService.getMessageRelations(message)));
let hasUnReadMessages = await Promise.all(messages[1].map(async message => await msgService.getMessageRelations(message)));
// Use `Promise.all` to wrap all the sub promises together into a whole Promise<any[]>
const readMessagesPromises = Promise.all(readMessages.map(message => msgService.getMessageRelations(message)));
const unreadMessagesPromises = Promise.all(unreadMessages.map(message => msgService.getMessageRelations(message)));

let [ hasReadMessages, hasUnReadMessages ] = await Promise.all([ readMessagesPromises, unreadMessagesPromises ]);

const formatMessage = message => {
return {
Expand Down

0 comments on commit b088d30

Please sign in to comment.