Search code examples
asynchronousvonage

Convert the callback to async/await for nexmo.message.sendSms?


My nodejs app calls nexmo API to send SMS message. Here is the API:

nexmo.message.sendSms(sender, recipient, message, options, callback);

In the app, it is

const nexmo = new Nexmo({
                apiKey: "nexmoApiKey",
                apiSecret: "nexmoSecret"
            }, { debug: true });        

nexmo.message.sendSms(nexmo_sender_number, cell_country + to, message, {type: 'unicode'}, async (err, result) => {....});

Is there a way I can convert it to async/await structure like below:

const {err, result} = nexmo.message.sendSms(nexmo_sender_number, cell_country + to, vcode, {type: 'unicode'});
if (err) {.....};
//then process result...

I would like to return the message to parent function after the message was successfully sent out.


Solution

  • The nexmo-node library only supports callbacks for now. You'll need to use something like promisify or bluebird to convert the sendSms function to promises, and the use async/await with it. Here is an example using Node's promisify

    const util = require('util');
    const Nexmo = require('nexmo');
    
    const nexmo = new Nexmo({
                    apiKey: "nexmoApiKey",
                    apiSecret: "nexmoSecret"
                }, { debug: true });        
    
    
    const sendSms = util.promisify(nexmo.message.sendSms);
    
    async function sendingSms() {
      const {err, result} = await sendSms(nexmo_sender_number, cell_country + to, message, {type: 'unicode'});
      if (err) {...} else { 
        // do something with result 
      }
    
    }