Dark Knight
Dark Knight

Reputation: 1083

await not waiting to resolve promise

This is my small twilio function/class returning promise which I do import in another file. I am getting err and res here returning it in promise

class TwilioService {
  sendSms(to, message) {
    return this.twilio.sendMessage(sms,(err,res) => {
      return new Promise((resolve, reject) => {
        if (err) {
          console.log(err)
          return resolve(res)
        } else {
          console.log(res, 'ppppppppppppppppp')
          return reject(res)
        }
      })
    })
  }
}

Now this is my function where I am using that function.

But when I do console.log(sendSms) I get undefined in the console even I am returning promise from the twilio function. What I am doing wrong here.

import Twilio from '../../services/twilio'
const twilio = new Twilio()
const handler = async(request, reply) => {
  try {
    const sendSms = await twilio.sendSms(`+91${mobile}`, `Welcome to App. User ${verificationCode} as your signup OTP.`)
    console.log(sendSms, 'oooooooooooooooo')
  } catch(err) {
    console.log(err)
  }
}

Please help!!! Thank you

Upvotes: 0

Views: 314

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370609

You're returning the callback at the moment, which probably doesn't return a Promise - switch the order around, return the Promise that resolves when the sendMessage callback runs. Also note that you should reject if there an err and resolve with the res if there is no err, not the other way around:

class TwilioService {
  sendSms(to, message) {
    return new Promise((resolve, reject) => {               // switch these two lines
      return this.twilio.sendMessage(sms, (err, res) => {   // switch these two lines
        if (err) {
          console.log(err)
          return reject(res) // reject on error, don't resolve
        } else {
          console.log(res, 'ppppppppppppppppp')
          return resolve(res) // resolve when there's no error
        }
      })
    })
  }
}

Upvotes: 7

Related Questions