Call same promise inside `Then`

O'Dane Brissett :

I want to know if you can call the same promise twice like so

//receiver is sent if the mail should be sent to someone else and will have a
//different email boy

const body = (req.body.receiver) === undefined ? 'regular mail': 'admin email body'

//the sendEmail Function takes to, from and body arguments
await sendEmail(req.body.requestedBy, someEmailAddress, body)
        .then(info => {
          console.log(info)
         //a mail should be sent only to requester if req.body.receiver is present in the request
          if (req.body.receiver) {
            await sendEmail(req.body.receiver, someEmailAddress, body)
              .then(res => {
                console.log(res)
              })
              .catch(err => {
                console.log(err)
              })
          }
          return res.send(data)
        })
        .catch(err => {
          console.log('Error:', err)
        })

Of course this would be wrapped in an async function because the sendMail function i created returns a promise. Mail is sent via nodemailer.

Boric :

What you are doing in your example is not technically calling the same promise twice. You are calling the same function twice, sendMail. Each time you call that function, it returns a new promise.

So the answer is yes, you can call that function multiple times even though it returns a promise, because it will return a new promise each time.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7307&siteId=1
Recommended