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

Incorporate dynamic rules into a CSS stylesheet

I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I&a ...

Ways to extract values from a javascript hash map by exclusively incorporating an array

So here's the issue I'm encountering. Let's consider the following scenario: let surfaces: Map<any, any> = new Map([{"83.1" => Object}, {"84.1" => Object}]) let arr1 = ["83.1"] This is the desired o ...

The function element.innerHTML is invalid when trying to assign an object value as an option

Hey there! I'm currently working on a JavaScript project where I have an input that retrieves text from an array. Each option in the array needs to be linked to an object so I can utilize its attributes. const data = [ { name: "SIMPLES NACION ...

After the page has finished loading, the JavaScript code is not able to

I have created a dynamic jobs list from a database that includes conditional salary reporting based on union type. I decided to build the dataset in the page load section of the CS page for output to a label on the ASPX page to handle the conditional state ...

Tips for combining Nuxt with Vue Cli 3

section: My current setup involves utilizing Nuxt.js to set up my Vue application. I'm curious if it's feasible to incorporate Nuxt into a Vue Cli 3 project in order to leverage the advantages of both platforms. Surprisingly, there doesn't ...

Is there a library available that can assist me in writing JavaScript code within C#?

Currently, I am in search of a tool that can assist me in writing C# code that will automatically convert to JavaScript. The main benefits I am seeking are improved code-completion and type-safety. Specifically, I am interested in the following features: ...

IE11 not running Angular code inline as expected

Currently in the process of developing an AngularJS application, I came across a strange issue that I have never encountered before. It may be a simple fix, but I am unsure of the exact terminology to search for the right solution, so I apologize in advanc ...

Tips for synchronizing the bounding box rotation and dimensions of a fabric group with its objects

Current version of fabricjs is 4.2.0 In the image provided, you can see a Text and Rectangle grouped together, both of which are rotated. It seems logical that the Bounding Box of the group should also be rotated accordingly. However, this is not the case ...

"Multiple instances of JavaScript files seem to be present when using Ajax navigation

Having some difficulties with AJAX navigation. The issue is that the JavaScript files loaded remain in the browser even after the new content is loaded, even when they are no longer in the DOM. These files appear as VM files in the browser console and cont ...

What is the best way to include a second (concealed) value in a cell using datatables

Query: How can I send specific cell values to a controller using POST method, where one value is visible and the other is hidden? For instance, each cell contains both Time and Date data but only the Time is displayed in the datatable. I need to post both ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

Using the DRY principle in JavaScript to handle dynamic fields

Recently delving into Javascript, I encountered a dynamic field script that allows for adding and subtracting fields with the click of a button. The functionality is effective and serves its purpose well. $(document).ready(function() { var max_fields ...

Updating a nested document within an array - Utilizing MongoDB with the Node.js driver

I am struggling to achieve the following task: locate a document with a specific id, then find the corresponding document in the legacy array based on a shortID, and update the sets array of that matched embedded document. For some reason, I can't se ...

"JavaScript throws an 'Undefined' error when trying to access a basic

I am struggling with a basic set of HTML and JS files that are not functioning properly, and I can't seem to pinpoint the issue: <html> <head> <script type="text/javascript" src="data.json"></script> < ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

Discover classes dynamically and eliminate redundant div elements

I am facing an issue with a JSON request that dynamically generates search results within div elements. The search results contain duplicate classes, all starting with "lid". How can I programmatically identify and remove all but one of the duplicate class ...

What is the best way to assign an object variable within an array state?

My current state looks like this: const [tags, setTags] = useState([{id: 1, label: "random"}, {id: 2, label: "important"}]) const [input, setInput] = useState("") const [selectedTag, setSelectedTag] = useState([]) In addition ...

Passing no data in Angular.js ui-router.Angular.js ui-router

Within my Ionic application, there is a need to pass parameter(s) from one sub-view to another. Initially, the parameters are successfully passed as expected. However, upon returning to the first sub-view and then navigating to another sub-view, the parame ...

Issue encountered while attempting to adjust a date (the modification was incorrect)

I am currently working on developing a calendar feature using Angular. Part of this project involves implementing drag and drop functionality to allow users to move appointments from one day to another. However, I have encountered a strange issue. When at ...