Search code examples
feathersjs

How do I wait for each of these promises to execute asynchronously?


conversation.user and conversation.secondUser are appended to the conversation object but the nested messages loop executes after the response is sent to the client.

    find: [
        async (context) => {
            await Promise.all(context.result.data.map((conversation) => {
                return context.app.service('users').get(conversation.userId).then((data) => {
                    conversation.user = data;

                    return context.app.service('users').get(conversation.secondUserId).then((data) => {
                        conversation.secondUser = data;

                        return conversation.messages.map((message) => {
                            return context.app.service('users').get(message.userId).then((data) => {
                                console.log(data);
                                message.user = data;
                            });
                        });
                    });
                });
            }));

            context.dispatch = context.result;
            return context;
        }
    ],

Solution

  • Two things:

    1. You forgot a Promise.all in the last section
    2. You are making your life harder by not fully making use of async/await

    This should work:

    find: [
      async (context) => {
        await Promise.all(context.result.data.map(async (conversation) => {
          const data = await context.app.service('users').get(conversation.userId);
          const secondData = await context.app.service('users').get(conversation.secondUserId);
    
          conversation.user = data;
          conversation.secondUser = secondData;
    
          await Promise.all(conversation.messages.map(async (message) => {
            const data = await context.app.service('users').get(message.userId);
    
            console.log(data);
            message.user = data;
          }));
        }));
    
        context.dispatch = context.result;
    
        return context;
      }
    ]