如何等待每个承诺异步执行?

时间:2018-05-29 11:17:06

标签: feathersjs

conversation.user和conversation.secondUser附加到会话对象,但嵌套的消息循环在响应发送到客户端后执行。

    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;
        }
    ],

1 个答案:

答案 0 :(得分:1)

两件事:

  1. 您在上一节
  2. 中忘记了Promise.all
  3. 由于没有充分利用async/await
  4. ,你的生活更加艰难

    这应该有效:

    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;
      }
    ]