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

A Guide to Importing CSV Data Into a Datatable

Is there a way to efficiently import data from a CSV file and display it in a table using the datatables plugin? Currently, I have a fixed table structure: <table id="myTable" class="table table-striped" > <thead> ...

redux - managing asynchronous storage using key-value pairs

Utilizing associative arrays with redux and storing them in async storage for later retrieval is my current challenge. When using redux, I am able to quickly access the values and efficiently map the content into cards in my react native app. However, aft ...

What is the best way to export my mongo schema to a file and then utilize it for inserting data?

I've been encountering difficulty when attempting to insert data into my collection. I'm not entirely sure if I'm doing it correctly, so I apologize for the vague request. Hopefully, by providing you with my code, you can help me understand ...

Unable to cancel the RTK query request

It's quite a dilemma. I need to handle the request differently when there is no user present. I've attempted different approaches like this and that const { data: carts = [] as ICart[], isFetching } = api.useGetCartProductsQuery(user.id, { skip: ...

The Mystery of Socket.io Random Disconnects (version 1.0.6)

Currently, I am utilizing the most recent version of socket.io (1.0.6) to develop an online multiplayer game using Phaser and Node. One issue that has arisen is that after the clients connect, they will sporadically disconnect without any specific pattern. ...

Restrictions on AngularJS animation for a specified class

Greetings! I am curious to know if there is a method to prevent Angular from automatically adding extra classes to an element for animation purposes. For example, when an element already has a CSS transition set and I apply another class using ng-class, A ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

Building dynamic charts using JSON data in Oracle JET

I am attempting to populate a pie chart using JSON data retrieved from restcountries.eu/rest/v2/all. I use $.getJSON to fetch the data, create a temporary array as the data source, and then bind it to the pie chart. However, I seem to be encountering an er ...

Flattening an array of Map in Typescript involves combining all the

I am working with an array containing entries of type Map<string, number> Is there a way to flatten this array into a single map? Map<string, number>[] converted to Map<string, number> Appreciate any help on this matter. ...

Having trouble retrieving the NextAuth session data within Next.js 12 middleware

I've been working on implementing route protection using Next.js 12 middleware function, but I keep encountering an issue where every time I try to access the session, it returns null. This is preventing me from getting the expected results. Can anyon ...

Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state. When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here ...

Modifying the maxHeight property of the angular-gantt component does not yield any noticeable changes

I am currently experiencing issues with dynamically changing the height using the angular-gantt library. Despite setting a new value for the maxHeight attribute in the controller, it does not reflect on the view as expected. I have seen this feature work i ...

Executing a mutation upon mounting using React Apollo 2.1's Mutation component: A Step-by-Step Guide

Currently transitioning from Relay to React Apollo 2.1, and I've encountered a questionable situation. Situation: Certain components should only be displayed if the user is authenticated with an API key. To handle this, there's an Authenticator ...

What is the best way to verify the presence of # in a URL?

Every now and then, due to caching issues, I find myself adding a # to my URL, like so: http://www.example.com/#lang=3201954253 My goal is to find and remove the #lang from the URL if it is present. ...

In JavaScript, a true statement does not trigger a redirect

<label>Username:</label> <input name="username" id="username" type="text" value="testuser"> <label>Password:</label> <input name="password" id="password" type="password" value="test123"> <input value="Submit" name="su ...

Error in Sequelize and Express JS: Cannot access undefined properties while attempting to read 'findAll'

I am currently facing an issue while working with Express JS and Sequelize in connection to a MSSQL database. The error message "Cannot read properties of undefined (reading 'findAll')" is blocking me from making any requests. Can anyone provide ...

Alert for any shift in the main task at hand

As a beginner in mobile development, I kindly ask for some understanding if I overlook any obvious details. My main objective now is to find a way to monitor a foreground task on both iOS and Android. To elaborate, I want my program to perform the followi ...

Acquire Content using jQuery and Navigate page horizontally

I am trying to achieve a unique effect by capturing content x and horizontally scrolling the page while the mouse is in motion, similar to swiping on a tablet. It seems simple enough.. Capture clientX on mousedown, ScrollLeft by ClientX while moving, Di ...

The function is missing from the object, leading to a script error with jQuery

When using different versions of jQuery, I encountered some issues with saving changes in my application. Initially, with jquery-1.4.4.min.js, everything worked except for the save function due to an error I made. However, when switching to jquery-1.7.1.mi ...

MUI Autocomplete causing a never-ending cycle of requests

One of the challenges I'm facing involves an Autocomplete component in my code. Here's a snippet of the code: <Autocomplete filterOptions={(x) => x} options={items} getOptionLabel= ...