I am facing an issue where I need to send different SMS messages to different recipients synchronously, but my current implementation using async/await is not producing the expected results.
Below is the code snippet causing the problem:
Upon querying for qualified users,
if(userQualifies) {
try{
await insertIntoTable();
} catch(err) {
console.log(err);
}
}
async function insertIntoTable(){
try{
await db.any(QUERY TO INSERT)
.then(async function(idCreated){
try{
var params = {
'messagingServiceSid': 'XXXXXXXXXX',
'to': ['1' + phone],
'body': message,
}
await sendMessage(params);
}catch(error){
console.log(error);
}
})
} catch(err){
console.log(err);
}
}
async function sendMessage(params) {
console.log('Im on sendMessage');
return client.messages.create(params)
.then( msg => {
console.log("SUCCESS:");
})
.catch(err => {
console.log("ERROR:");
});
console.log("message sent");
return 'done';
}
When executing this code, the log displays 'Im on sendMessage' after inserting into the table, but fails to send the message immediately. Instead, it queues all messages and sends them simultaneously at the end.
How can I modify the code to ensure that messages are sent in a synchronous manner as the flow transitions from insertIntoTable()
to sendMessage()
?