Aysnc for each callback issue

34 Views Asked by At

I am using async for each to achieve some task the problem i am facing is that the final call back never executes

Scenario : i have list of contacts and want to send message to all contacts in parallel and when message is send want to store the response in array and than want to perform some action on final call back

sms.js

function SmsService() {}

SmsService.prototype.sendSms = function(value, callback) {

       client.messages
            .create({
                body: value.body,
                from: value.from,
                to: value.to
            })
            .then(message => {
                console.log('meesage going', message.sid);

                callback(null,message.sid)
            })
            .catch(e => {

                callback(null,'not send')

            })
   }


module.exports = SmsService;

sender.js

  var SmsService = require(path.resolve(__dirname, './sms'));
     var smsService = new SmsService();
     var data = [{body:'1232324',from:'+12323123',to:'+12312323'},
     {body:'112123234',from:'+123123123',to:'+123213123'}, {body:'12sadasdasd34',from:'+112123123',to:'+1223213123'}]

     async.forEachOf(data, function (value, i, cb) {
        console.log('started',i)
            smsService.sendSms(value, function(error, result) {
                console.log('sending',i,value.to)//only get result for first item 
                results.push(result)
                cb()
            })

     }, function (err) {
        if (err) console.error(err.message);
         console.log('all done')//never executes
        console.log(results);//never executes
    });

If I move the async part to SMS service it works fine but I want to keep separate the SMS service

1

There are 1 best solutions below

0
Shubham Jain On

You can try something like this.

sms.js

function SmsService() {}

SmsService.prototype.sendSms = function(value, callback) {

    return new Promise((resolve, reject) => {
        // Do async job
        client.messages
            .create({
                body: value.body,
                from: value.from,
                to: value.to
            })
            .then(message => {
                console.log('meesage going', message.sid);
                resolve(callback(null,message.sid))
            })
            .catch(e => {
                reject(callback(null,'not send'))
            })
    })
}
module.exports = SmsService;

sender.js

var SmsService = require(path.resolve(__dirname, './sms'));
var smsService = new SmsService();
var data = [{body:'1232324',from:'+12323123',to:'+12312323'},
            {body:'112123234',from:'+123123123',to:'+123213123'}, 
            {body:'12sadasdasd34',from:'+112123123',to:'+1223213123'}];
var promises = [];
data.forEach(async function (obj, index) {
    console.log('started',index)

    promises.push(await smsService.sendSms(obj, function(error, result) {
        console.log('sending',i,value.to)//only get result for first item 
        results.push(result)
    }));
});

Promise.all(promises).then(function () {
        console.log("Messages sent")
}).catch(function (err) {
        console.log("Messages not sent")
})