Using a combination of functions to ensure synchronicity in JavaScript operations

Here is the function I have created:

$scope.saveManualResendDraft = function(todo) {
    if ($scope.editMode) {
        updateStartJobManual();
        byeSendManualInputDirectly();
    } else {
        console.log('bye');
    }
};

I have defined two functions called updateStartJobManual() and byeSendManualInputDirectly().

I want to ensure that the first function completes fully before moving on to the second. Is it possible to achieve this using promises? Can someone provide me with a sample code snippet?

function byeSendManualInputDirectly() {
    if ($window.confirm("Do you want to send this message?"))
        addProfSms();
    else
        console.log('no');
}

function addProfSms() {
    $http.post('/api/sendprofsms', $scope.draft).then(function(response) {
        swal("Good job!", "Message sent!", "success")
        //  $state.reload();
    });
}

function updateStartJobManual() {
    $http({
        method: 'POST',
        url: '/api/updatestartjobmanual',
        data: $scope.draft
    }).then(function(response) {
        $scope.currentItem = response.data;
        $scope.todos[$scope.currentItemIndex] = response.data;
        $scope.editMode = false;
        console.log('draft:', response.data);
        $state.reload();
        // toastr.success('Updated Successfully');
    }, function(response) {
        console.log('error');
    });
}

Answer №1

Your current code is set up to run updateStartJobManual and byeSendManualInputDirectly synchronously.

If these functions involve promises, they may terminate prematurely while a background job is still in progress. To avoid this, we can chain the promises so that they execute one after another.

Let's consider how byeSendManualInputDirectly is structured:

function byeSendManualInputDirectly(){
   return $http.post('myApiAddress', {myParam: true});
}

In this setup, the function returns a promise.

To combine updateStartJobManual and byeSendManualInputDirectly, you can do the following:

updateStartJobManual().then(function(){
   byeSendManualInputDirectly()
});

I recommend reading up on articles about promises to fully understand their functionality (you can refer to this documentation on $q, the promise library used by AngularJS).

Based on the OP's code:

Add a return statement to your updateStartJobManual function like so:

function updateStartJobManual() {
    return $http({
        method: 'POST',
        ...
}

In your saveManualResendDraft function, incorporate a then() to handle the promise:

$scope.saveManualResendDraft = function(todo) {
    if ($scope.editMode) 
        updateStartJobManual().then(byeSendManualInputDirectly);
     else 
        console.log('bye');        
};

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

Troubles with setting up slash commands in discord.js v13

I am encountering an issue while trying to deploy a slash command. The error message DiscordAPIError[50035] is displayed, stating "Invalid Form Body guild_id[NUMBER_TYPE_COERCE]: Value \"undefined\" is not snowflake." const path = require('n ...

Accessing a file located in a specific directory using the node fs module

Currently, I am attempting to access a file from my local system using the 'fs' module in node.js. However, I have encountered an issue where the 'fs' module does not seem to function properly when an absolute path is provided. Here is ...

Struggling with validating forms with JavaScript

I'm having trouble with the following JavaScript code: <script type="text/javascript"> function checkDetails(search) { var search = documment.getElementById('query'); if(search.value ==''||search.val ...

Interact with Excel-VBA drop down button using IE (SPAN NG-IF) in an AngularJS application

Is it possible to make a button click work with the SPAN NG-IF feature? Am I approaching this issue incorrectly? The name "Lõuna port" changes when something else is clicked in the drop-down menu. I have a list of all the names but can't figure out h ...

Connect and interact with others through the Share Dialogues feature in the

Update - Edit I'm just starting to explore the concept of share dialogues and I want to integrate it into my website. On my site, there is a reaction timer game that shows the user's reaction time in seconds in a modal popup. I want users to be ...

Generating various arrays of data

I am currently facing an issue with creating separate datasets based on the month value. Despite my efforts, all month values are being combined into a single dataset in my code. Any assistance in dynamically generating different datasets would be greatly ...

How to submit form data with a POST request in Flask using fetch without having to reload

Despite reading numerous similar questions, I am still unable to determine how to achieve my goal. I have multiple forms on a single page and I am trying to submit data from each form without refreshing the page. Below is an example of one of the five form ...

What is the correct way to align an InputLabel in Material UI?

https://i.stack.imgur.com/Uafr1.png Looking for advice on styling the InputLabel in my code to improve its appearance. Code snippet below: <FormControl fullWidth> <InputLabel >Select EPE</InputLabel> <Select ...

What is the process for integrating Firebase into $asyncValidators?

I am looking to implement a feature in my Firebase app that ensures usernames are unique. I want the user to be promptly informed if a username is already taken or not. I have been exploring AngularJS's ngModel as it offers an asyncValidator in its co ...

Customize cell color in angularjs and ui-grid

In my ui-grid, I have two columns - firstName and lastName. The background color of the firstName column is set to blue. When I click on the header of the lastName column, I want to change the background color of the lastName column to blue and return the ...

RobotFramework encounters difficulty locating an element using JavaScript

After working with RF for the past few weeks, I came across a persistent issue that has been bothering me. I keep getting the following error: The element with the locator 'XXX' (just a template) cannot be found. Upon investigating the span tha ...

How can I load a function from the HTML file that is being loaded using .load() in jQuery?

Within my main window main.html, there is a div button that, when clicked, loads another html file into a large div. This is achieved using the .load() function: $('#mainpanel').load("search.htm"); The "search.htm" file contains a function cal ...

Cross-Origin Resource Sharing (CORS) for enabling the remote inclusion of JavaScript

I have a unique javascript widget that is designed to be embedded from an external server (e.g. ) The javascript, which contains a simple alert('hello'), is generated by a php script. Upon execution, I include a header like this: <?php heade ...

What are some solutions for resolving an infinite loop of axios requests?

I am currently in the process of developing a web app for Spotify using its API. I have encountered an issue where the handleClick function in Albums.js is being called repeatedly when trying to make a get request for specific artist album data. Could this ...

Error: The function .default.auth.signout is not recognized in the REACT and Firebase environment

I've come across several error questions on StackOverflow, but most remain unanswered. The ones that are answered don't seem to solve my issue. I need help debugging this particular error. In my REACT project using Firebase, I'm working on ...

Obtain the origin of the image using dots in Javascript

Sharing my experience with setting a background image using Javascript. Initially, I tried using two dots like this: .style.backgroundImage = "url('../images/image00.jpg')" However, it did not work as expected. So, I removed one dot: .style.ba ...

Is it possible to set environment variables in Next.js outside of the pages directory?

Are there alternative methods for setting environment variables outside of a pages directory in NextJS? I have a utility function that defines the base API route in one centralized location. However, since this is a utility function and not associated with ...

The art of sketching precise lines encircling a circular shape through the

What is the best way to use a for loop in JavaScript to draw lines around a circle, similar to those on a clock face? ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

Is it possible to blur all elements of a form except for the submit button?

Can someone help me with a form issue I am facing? <form> <input type="text>' <input type="submit">' </form>'' After submitting the form, I would like to blur the entire form: $(this).closest('form') ...