Neglecting the Outcome of Async/Await

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()?

Answer №1

While I may not fully understand the intricacies of your code, allow me to present an async pattern that ensures one asynchronous action in an array completes before moving onto the next:

async function deliverMessage(parameters) {
   console.log('Executing deliverMessage function');
    return client.messages.create(parameters)
        .then( msg => {
            console.log("SUCCESS:");
        })
        .catch(err => {
            console.log("ERROR:");
        });
}

const messageArray = [{
                 'messagingServiceSid': 'XXXXXXXXXX',
                 'to': ['1000000'],
                 'body': 'first message',
              },{
                 'messagingServiceSid': 'XXXXXXXXXX',
                 'to': ['2000000'],
                 'body': 'second message',
              },
              {
                 'messagingServiceSid': 'XXXXXXXXXX',
                 'to': ['3000000'],
                 'body': 'third message',
              }];

async function processMultipleMessages(messages) {
  for (let msg of messages) {
    await deliverMessage(msg);
  }
}

processMultipleMessages(messageArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

Put emphasis on the input field - React component

My React component features an input field with a disabled attribute. When the component is clicked, the input becomes enabled for the user to type in. I have successfully implemented this functionality so far, but now I need to focus on the input field on ...

New jQuery div elements do not have animations when using $(document).on

After creating an animation function that worked well with hovering over squares and leaving a trail, I later needed to add or remove squares based on the page size. Seeking help from here, I discovered my bind animation function wouldn't work on new ...

Tips on validating if a form has already been submitted using JavaScript and AJAX to prevent duplicate submissions

Exploring the world of web development, I stumbled upon a fascinating component - forms in JavaScript or jQuery. However, here lies my dilemma: In JS: const themeFolder = object_name.templateUrl; const urlAjax = themeFolder + '/FormHandler.php&apos ...

Sending a message in the DELETE route using express.js

I'm having trouble displaying a message after deleting a user. I attempted to use req.session properties and then retrieve them in the GET route, but they seem to not be available. Can anyone suggest a solution for fixing this code? router.get("/", ...

What is the purpose of assigning scope.property to scope.property() in order for the expression to function properly?

I have encountered an interesting situation with the directive below. In order for my expressnum function to work in the template, I had to include the line scope.expressnum = scope.expressnum();. It does what I need it to do, but I'm not entirely sur ...

How to remove checkbox border using HTML, JavaScript, and CSS

Is it possible to remove the square border from a checkbox in HTML? ...

Creating a Javascript function to turn lights off using CSS manipulation, similar to the feature found

Is there a way to use JavaScript to obscure all elements on a page except for one specific HTML element? This web application is optimized for Chrome, so CSS3 can also be utilized. ...

Ways to automatically update property value in MongoDB once a particular date is reached

Is it feasible to schedule a future date for a document in MongoDB, such as 30 days from the current date, and then automatically update another property of the document when that future date arrives? For instance: creating an event document setting the ...

Scrolling horizontally in a container using the mouse wheel

Is there a way to enable horizontal scrolling in a div using the mouse wheel or drag functionality with jQuery? I attempted using draggable, but it did not work effectively in my specific code scenario. Currently, I have a horizontal scrollbar. Are there ...

How can I simulate a callback function that was not tested?

Currently experimenting with the method below: startScriptLoad(): void { const documentDefaultView = this.getDocumentDefaultView(); if (documentDefaultView) { const twitterData: ICourseContentElementEmbedTweetWidgetData = this.getTwitterWid ...

The Angular.js UIBootstarp Timepicker is displaying the "ng-invalid" class when used with an input type of "number"

Currently, I am working on incorporating a time picker using UIBootstrap and angular.js. By default, the timepicker utilizes {{input type="text}} for capturing hours and minutes. However, since I intend to use this feature on mobile devices, I need to di ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...

How to Convert Python Lists into JavaScript?

octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random. ...

The Enigma of AngularJS Coding

Check out this code snippet. $scope.$watch('year', reloadData); $scope.$watch('month', reloadData); $scope.year = 2017; $scope.month = 1; var reloadData = function() { /* Refresh Data */ } var init = function() { $scope.year ...

Getting the result from a JavaScript request, whether it's synchronous or asynchronous

This code snippet involves a function that starts with a synchronous comparison test == 0. If the comparison is true, it returns one piece of content; however, if it's not, an asynchronous request is made. The goal here is for the latter part to retur ...

There is no 'Access-Control-Allow-Origin' header found on the requested resource in Heroku for Node.js

Here is the header setup in my Node.js API app: res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested, Content-Type, Accept Authorization" ); ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...

Even after hitting ctrl+z, Node.js continues to listen on the port

I've been exploring some features of Node on Ubuntu, and I encountered an issue where even after pressing ctrl+z in my console to stop the server (to update my code changes), Node would still be listening on port 3000. This meant that every time I nee ...

Adding elements to a list using the appendChild method

Hey there! I have a bunch of images and I'm trying to create a navigation list item for each image. Here's the code I currently have: var bigImages = $('#imagesList li img'); // grabs the Big Images Next, I've set up a ul with t ...