Reputation: 179
I'm trying to iterate through a local JSON file of objects with names and phone numbers. In my loop, I'm calling Twilio's sendMessage function to send a message to each number from my Twilio Number. The code below runs but only sends a message to the first number in the JSON file. Is something wrong with my approach or is this due to a restriction with Twilio's API? If so, is there a workaround? Thanks.
admins.forEach(function(admin) {
var phoneNum = admin.phoneNumber;
var adminName = admin.name;
var messageBody = "Hello there, " + adminName;
client.sendMessage({
to: phoneNum, // Any number Twilio can deliver to
from: TWILIO_NUMBER,
body: messageBody // body of the SMS message
}, function(err, responseData) {
if (!err) {
console.log(responseData.from);
console.log(responseData.body);
}
});
})
Upvotes: 0
Views: 378
Reputation: 73055
Twilio developer evangelist here.
That loop should work, but I noticed in your comment on Ben's answer that you are still sending these messages from a trial account. There are limitations on trial accounts such that you can only send messages to numbers that you have verified as yours with Twilio (to avoid spam).
My guess is that you have only verified the first number in your list so the remaining messages are failing to send at the API level.
You'll either need to verify some of the other numbers you are using or upgrade your account in order to send messages to all the numbers you want.
Let me know if that helps at all.
Upvotes: 1
Reputation: 5074
Regular loop would not work since it doesn't wait for all async request sendMessage() calls to finish. One of the simple ways to do it is to use some library that you can control the flow of the loop such as async.each(). Here is the revised code usning async.each():
var async = require('async');
async.each(admins, function(admin, eachCb) {
var phoneNum = admin.phoneNumber;
var adminName = admin.name;
var messageBody = "Hello there, " + adminName;
client.sendMessage({
to: phoneNum, // Any number Twilio can deliver to
from: TWILIO_NUMBER,
body: messageBody // body of the SMS message
}, function(err, responseData) {
if (!err) {
console.log(responseData.from);
console.log(responseData.body);
}
eachCb(null);
});
}, function(err) {
console.log('all done here')
});
Upvotes: 1