Home > Net >  how to put await in then portion under Promise.all
how to put await in then portion under Promise.all

Time:06-12

In the following code, I used Promise.all to enable async called when calling map, but in the then portion, i need another call to await, the syntax does not allow me to do that, what's the way to enable await under then branch? Alternatively, is there more elegant way to achieve the same purpose of my code without introducing so many different constructs like Promise.all?

 const handleSend = async ({ text, attachments }) => {
        const attachmentsArr = null;

        Promise.all(attachments.map(async a => {//<--use Promise all for async within map
            const isImage = a.type.startsWith('image/');
            let response = null;
            if (isImage) { response = await channel.sendImage(a); } else { response = await channel.sendFile(a); }
            return {
                name: a.name,
                path: response.file,
                size: a.size,
                isImage
            };
        })).then(attachmentsArr => {
            await channel.sendMessage({ //<--can't use await here
                text,
                workspaceId: '1234567',
                attachments: attachmentsArr
            });

        }

        );
    };

CodePudding user response:

I would write it like this

const handleSend = async ({ text, attachments }) => {

  const promisesArray = attachments.map(async a => {
    const isImage = a.type.startsWith('image/');
    let response = null;
    if (isImage) {
      response = await channel.sendImage(a);
    } else {
      response = await channel.sendFile(a);
    }
    return {
      name: a.name,
      path: response.file,
      size: a.size,
      isImage
    };
  });

  const attachmentsArr = await Promise.all(promisesArray);

  await channel.sendMessage({
    text,
    workspaceId: '1234567',
    attachments: attachmentsArr
  });

};

But, you should check attachmentsArr and see how to know when is empty to send null.

CodePudding user response:

Mixing async/await with then can be confusing. You can instead write it all in async/await syntax like Braian's answer, or in then syntax like this:

const handleSend = ({ text, attachments }) => {
  Promise.all(attachments.map(async a => {
    const isImage = a.type.startsWith('image/');
    let response = null;
    if (isImage) { response = await channel.sendImage(a); } else { response = await channel.sendFile(a); }
    return {
      name: a.name,
      path: response.file,
      size: a.size,
      isImage
    };
  })).then(attachmentsArr => {
    return channel.sendMessage({ // <--- Return a promise
      text,
      workspaceId: '1234567',
      attachments: attachmentsArr
    });
  }).then((result) => { // <--- Operate on the resolved value
    // Do something with result
  });
};
  • Related