Waiting to fulfill promises in a function does not postpone the function's execution

I'm having difficulty with deferred promises. I am faced with a rather messy string:

me, company name, SSQ ID, the company you are working for (Extraction/XTR/8North) and the tier assigned to your company in question #17.

|Y132~
|Y133~

|Y134~

|Y138~
|Y139~
|Y140~

|Y141~
|Y142~
|Y143~

which requires me to replace each occurrence of "|Y000~" with a URL link. The code for this part is functional. However, I am struggling to implement a promise that waits for the function (involving deferral of multiple promises) to complete before proceeding further.

My "convertString" function has the following snippet:

getAllClusterLinks(indices, returnString)
returnString = $scope.returnString;

Below is the convertString function code:

function convertClusterText(questions, field) {
    angular.forEach(questions, function (value, key) {
        if (value.vchTextBeforeQuestionCluster != null) {
            var str = value.vchTextBeforeQuestionCluster;
            // Code to replace various elements in the string
            if (returnString.indexOf("|Y") >= 0) {
                // Handling links in the string
                if (indices.length > 1) {
                    // Calling getAllClusterLinks function
                    getAllClusterLinks(indices, returnString)
                    .then(function () {
                        returnString = $scope.returnString;

                    })
                           value.vchTextBeforeQuestionCluster = returnString;



                }
                else {
                    // Getting hyperlink
                    // Setting up link in the string
                }

            }
            else {
                // Handling when no |Y code is found
            }


        }
    });
};

It is crucial for "getAllClusterLinks" to finish executing before moving on to the next line. Here is the code for "getAllClusterLinks":

function getAllClusterLinks(indices, returnString) {
    var promises = [];
    var times = 0
    var endIndex = 0;
    angular.forEach(indices, function (value, key) {
         // Looping through indices and getting link codes
        var promise = getClusterLinks(linkCode, returnString);
        promises.push(promise);
    })

    return $q.all(promises);
}
function getClusterLinks(linkCode, returnString) {
    var deferred = $q.defer();
     // Code to fetch hyperlink data and set up link
    return deferred.promise;

}

The current code functions correctly, but I need it to finalize before setting the line

returnString = $scope.returnString;
.

I attempted this approach, which did not yield the desired result:

                     getAllClusterLinks(indices, returnString)
                    .then(function () {
                        returnString = $scope.returnString;

                    })

Your help in resolving this issue would be greatly appreciated!

Answer №1

After calling $q.all(promises), a promise is returned. You can then utilize the then() method.

 getAllClusterLinks(indices, returnString).then(function() {
     returnString = $scope.returnString;
});

[https://docs.angularjs.org/api/ng/service/$q][1]

An important note: Make sure to resolve your deferred object

On a side note: It appears that success() has been deprecated and it is recommended to use .then as an alternative

function getClusterLinks(linkCode, returnString) {
    var deferred = $q.defer();
    $scope.returnString = returnString;
    contractorService.gethyperlink(linkCode)
    .success(function (data) {
        var vchUrl = data[0].vchUrl;
        var end = vchUrl.length;
        var docID = vchUrl.substring(vchUrl.indexOf("=") + 1, end);
        var vchLinkName = data[0].vchLinkName;
        var yay = '<a href="" ng-click="getDocument(' + docID + ')">' + vchLinkName + '</a>';
        var yCode = "|Y" + linkCode + "~";
        $scope.returnString = $scope.returnString.replaceAll(yCode, yay);
        deferred.resolve(); // make sure to resolve here
    })
    return deferred.promise;

}

Answer №2

Consider placing the following code inside a then() callback:

getAllClusterLinks(indices, returnString)
    .then(function() {
        returnString = $scope.returnString;
    });

To learn more about promises in Angular, check out the official documentation

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

What is the method used by threejs to position a mesh within a scene when no coordinates are provided?

I'm embarking on a personal project using threejs and I'm seeking clarification on how the threejs add method functions when adding to the scene. In a small example, a scene and camera are created with near and far plane units set from 0.1 to 10 ...

Why is it that the HttpClient constructor in Angular doesn't require parameters when instantiated through the constructor of another class, but does when instantiated via the 'new' keyword?

I am trying to create a static method for instantiating an object of a class, but I have encountered a problem. import { HttpClient } from '@angular/common/http'; export MyClass { // Case 1 public static init(): MyClass { return this(new ...

Using & in text leads to segmentation upon transmission to the server

When utilizing ng-resource to send a string to the server, I encountered an issue. If I include &amp; in the string, anything following it is not transmitted to the server. For instance, sending this string: "This section of the string is visible &am ...

What is the significance of utilizing response.json() for accessing JSON objects on both the server and client sides?

Just starting out with the MEAN stack, I've included my API code below where I'm using res.json(random) to send a random password. module.exports.changePass = function (req, res) { console.log(req.body.email) db.user.find({ where: { name: ...

What could be the reason for the timeout function in my Angular application not working as expected?

I've created a basic controller to handle a countdown timer. Upon running the code, I notice that only one "tick" is displayed in the console. Ideally, I would like to see a "tick" every 5 milliseconds. .controller('Countdown', function($s ...

Ensure Rxjs waits for the completion of the previous interval request before moving forward

Scenario: It is required to make an API call every 3 minutes to update the status of a specific service within the application. Here is my existing code snippet: interval(180000) .subscribe(() => this.doRequest ...

What is the best way to change a javascript string into HTML so that it can be shown in a form?

I am struggling to find a solution to this issue. I am fairly new to jQuery and JavaScript, so please forgive me if my question seems basic. I am trying to call a cfc (ColdFusion) using jQuery and retrieve HTML data. However, when I receive the data, it ...

Is it feasible to display two slides simultaneously in the carousel?

I have recently delved into learning about Angular.js and am currently utilizing the Carousel control in Angular-ui. I am curious to know if it is feasible to showcase two slides simultaneously instead of just one? My intention is to present the images in ...

What could be causing the malfunction in one of the functions within my JavaScript code?

As a JavaScript beginner, I am currently working on creating a To-do App with JavaScript. Most of the functions are functioning perfectly except for one called doneTask at line 36. Despite numerous attempts to identify the issue, I have been unsuccessful s ...

Is there a way I can implement a user-friendly playlist feature in my object-oriented HTML5 JS audio player that allows users

I have created a functional audio player using HTML5 and Javascript, along with some basic CSS. However, I am looking to enhance it by adding a clickable playlist feature. I want the name of the currently playing audio track to be displayed, and users shou ...

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

Modify content on a link using AngularJS

Currently, my setup looks like this: HTML Code <div ng-app="home" ng-controller="customersCtrl"> <div ng-bind-html="home" id="content">{{content}}</div> </div> JS Code angular.module('home', []).controller('c ...

Exploring the functionality of jQuery by incorporating a variable into the selector

I attempted to modify the src attribute of an image file using a variable, but it did not actually change. Can anyone pinpoint where I went wrong in using the variable? jquery var p2begen = "416"; $("[id=i'" + p2begen + "']").attr("src", "check ...

HTML/JS Implementation: Back to Top Visual Element

- This website appears to be quite simple at first glance. However, I have encountered an issue where every time I scroll down and then click on the "About" menu option, it abruptly takes me back to the top of the page before displaying the section with a ...

Submitting data using Angular's POST method

Disclaimer: As a front-end developer, my experience with servers is limited. I am currently working on an Angular 1.2 app that makes API calls to a different subdomain. The backend developer on the project has configured nginx to allow cross-domain reques ...

Tips for tailoring content based on screen size

I am looking for a way to display different content depending on whether the user is viewing my website on a large screen (PC/tablet) or a small screen (mobile). While my site is responsive and uses bootstrap, I have a lot of content that is only suitable ...

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

Determining the optimal number of rows and columns based on an integer value

Here's a brain teaser for you: /** * Let's figure out the optimal number of rows and columns for your garden to be as square as possible, based on the number of seeds you have. * * @param {number} seedCount - The total number of seeds in you ...

AngularJS Kendo UI: Elevating Your Web Development Experience

This is my first time working on an Angular Js application as part of a project requirement. I have been searching online for documentation on installing Kendo for Angular, but most resources seem to focus on Angular instead of Angular Js. Is it possible ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...