What is the best way to turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows:

return {
   item: null,
   get: function() {
     return item;
   },
   create: function() {
     if (this.get()){
         this.remove();
     }

     this.item = {};
   },
   remove: function() {
     var item = this.get();
     if (item) {
      this.item = null;
     }
   },
   add: function() {
     if (!this.get()) {
        this.create();
     }

     this.item.newprop = 'value';
   }
}
  1. I prefer to keep the object structure with its own actions and properties rather than changing to function declarations.

  2. The pattern of nesting functions like get inside create is original to my design. Does this approach have a specific name and is it considered an optimal way to handle function-black boxes?

  3. What would be the most effective method to incorporate Promises within each function so that they all return a Promise?

  4. Is it necessary to use bind for every then function call?

    For example:

create: function () {
    this.get()
        .then(remove)
        .then(function () {
            this.item = {}; // However, in this context, 'this' is undefined!!
        });
}

Answer №1

Each then callback function must include the use of bind:

var myModule = {
    item: null,
    get: function() {              
        return Promise.resolve(this.item);
    },
    create: function() {
        return this.remove().then(function() {
            this.item = {};
        }.bind(this));
    },
    remove: function() {
        return this.get().then(function(item) {
            if (item) {
                this.item = null;
            }
        }.bind(this));              
    },
    add: function() {
        return this.get().then(function(item) {
            return item || this.create();
        }.bind(this)).then(function() {
            this.item.newprop = 'value';
        }.bind(this));
    }
}                   
// Let's observe it in action:
myModule.create().then(function() {
    return myModule.get();
}).then(function(item) {
    console.log("After create: ", item);
    return myModule.remove();
}).then(function() {
    return myModule.get();
}).then(function(item) {
    console.log("After remove: ", item);
    return myModule.add();
}).then(function() {
    return myModule.get();
}).then(function(item) {
    console.log("After add: ", item);
});     

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

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...

Reducing div size when clicked - Using JQuery version 1.9

I am looking to make a specific div shrink in size, while keeping all the data visible, each time a user clicks on a certain icon with the class legend-icon. For example, I want the div with the ID #Chart to shrink when clicked. This is the HTML code: &l ...

Issues with the code: $("input[type=checkbox]:checked").each(function() { var checkboxId = $(this).attr("id"); });

When submitting a form, I need to retrieve the IDs of all checked checkboxes. Currently, $(this).id() is causing an error. What is the correct code to obtain the IDs of all checked checkboxes? $("#pmhxform input:checkbox:checked").each(function() { ...

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Preloading Vue dynamic routes for optimal performance

Currently dealing with a challenge on my Vue project and could use some help. I'm looking to prerender specific dynamic routes when I navigate to a particular route within the application. On the /works route, there's a list of items displa ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

How to verify CSRF protection on Node.js/Express endpoints

I have added csrf (cross-site request forgery) protection to my express application like this: ... app.use(express.csrf()); app.use(function (req, res, next) { res.cookie('XSRF-TOKEN', req.csrfToken()); next(); }); ... Everything is working ...

Unused function in Vue error compilation

I am facing an issue with the compiler indicating that the function 'show' is defined but never used. The function show is being used in HTML like this: <b-card> <div id="draw-image-test"> <canvas id="can ...

Is there a way to minimize superfluous re-renders in React without resorting to the useMemo hook?

I am currently evaluating whether I should adjust my strategy for rendering components. My current approach heavily relies on using modals, which leads to unnecessary re-renders when toggling their visibility. Here is a general overview of how my componen ...

Having trouble getting this JavaScript query to function properly

The initial div in the code snippet below showcases the name of a university. When this name is clicked, it activates the function display_people(). This function is responsible for displaying or hiding the individuals associated with that university. The ...

The list item click event is not triggered when new list items are added

I've run into a bit of confusion with my code. Everything seems to be working perfectly fine until I introduce new items. Take a look at a sample of my items However, once I make changes to my list, the click function stops working. Check out a sa ...

How can an Embedded React + JSS component safeguard generic elements such as <button> and <p> from being affected by the page's style?

I am facing a challenge with a React component that is being embedded in various webpages, either through an extension or as a third-party tool. Most of the styling for this component is done using JSS, ensuring unique class names that cannot be overridde ...

Even though there is an error in the line of code saying "Error in render: RangeError: Invalid array length", it still manages to perform its intended task

When trying to round a float number and display stars equal to that rating number, the code works as expected. Surprisingly, it also generates an error Error in render: "RangeError: Invalid array length" <p>Rating: <i v-for='n in Math.round( ...

show the attributes of an item contained within an array of objects

Hey there! I'm facing an issue with displaying the content of an object on my HTML page using React. So, here's what's happening: I can access the frontend properties in my object array, but when I try to loop through each element and displa ...

Alter the class generated by ng-repeat with a click

I currently have a dynamically generated menu displayed on my website, and I am looking to apply a specific class to the active menu item based on the URL (using ngRoutes). The menu items are generated from a $scope.menu object, so my initial thought was t ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Ways to display pictures by invoking an API within the antd item list container

Upon page load, I am fetching images from a database using an API. Now, my goal is to display these images within a Modal in Antd. How can I accomplish this with the code snippet below? const MyVehiclePage = (props) => { useEffect(() => { co ...

Storing user authentication tokens securely in session storage within Next.js can help maintain a

Is there a way to ensure that user data remains persistent even after a page refresh? I considered storing it in local storage, but that may result in a flash of unauthenticated content. Storing it in a cookie could also be problematic when working with ...