Generate a commitment from the function

I know the basics of JavaScript Promise and promise chain, but I'm looking to deepen my understanding. For example, take a look at the method provided below. It's in TypeScript, but can be adjusted for JavaScript ES6.

private InsertPersonInDB(p : Person) {    
     return this.db.find({                              //<- What does this return?
                selector: {objType: 'Person'},
                fields: ['_id'],
                sort: ['_id']
            }).then( result => {                         
                let allpersondIds : string[] = [];
                (result.docs).forEach(rec => {
                    allpersondIds.push(rec._id);
                });
                return allpersondIds;                
            }).then ( allpersonIdsInDB => {                
                var id = this.getIdfromPersonName(person.personName, allpersonIdsInDB);
                person._id = id;
                return this.db.post(person)            //<- Or does this return something else?
            }
}

//Calling function
for(let person of this.persons) {
    InsertPersonInDB(person).then(result => {
        console.log(result)
        //Some UI updates       
    }).catch(err => {
        console.log(err)
        //Some UI updates notifying user about failure  
    }); 
}

In this piece of code, there are two returns. First is

return this.db.find

which involves a promise from the find function.

And towards the end of the last then block, we have

return this.db.post(person)

This too deals with a promise in the form of the post function.

I have three questions:

1) When this method is executed, what exactly gets returned?

2) If the method instantly returns a promise, when do the subsequent thens get executed?

3) How should one go about restructuring a promise chain in a multi-layered application? For instance, some then blocks need to run in the service layer while others in the UI. What would be an effective approach to organizing promise-related code like this?

Answer №1

One way to tackle your questions is by experimenting with small examples to gain a better understanding. Creating a simple example can be a helpful way to test out how things work and observe the outcomes. Let's apply this approach to your question as well (check out https://plnkr.co/edit/K18o4Lp2jtUincjyG5wi?p=preview for a functional version; remember to open the console to view the results!):

function test() {
  return returnPromise().then((value) => {
    console.log('1st then, inside test(): ' + value);
    return 'Hello';
  }).then((value) => {
    console.log('2nd then, inside test(): ' + value);
    return 'world';
  });
}

function returnPromise() {
  return new Promise(function(resolve, reject) {
    resolve('start of new Promise');
  });
}

test().then((value) => {
  console.log('3rd then, after calling test: ' + value);
});

In relation to your queries:

  1. When you return a Promise along with its chained then functions, any additional then added to the returned Promise will continue the chain. This explains the behavior when using test().then(...).
  2. A Promise signifies that an action will occur at some undetermined time, only executing once the Promise resolves. Take a closer look at returnPromise to understand this concept. Here, we initiate a new Promise and immediately call the resolve method, prompting the Promise to resolve and trigger all attached then methods. Typically, a Promise undergoes an asynchronous operation before resolving, such as fetching data from a server.
  3. The suitability of your current approach hinges on the nature of your application and specific requirements. It is essential to clearly define roles and responsibilities to ensure an effective workflow.

Answer №2

1) A commitment that is fulfilled when the db.post(person) request successfully completes.

2) The function supplied to then(...) is triggered upon receiving a response or encountering an error from the db.post() invocation.

3) Unsure. There isn't a one-size-fits-all solution for this scenario. It hinges on the specific API functionality desired for users of this service.

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

Setting up Jest to run in WebStorm for a Vue project with TypeScript can be done through

I am struggling to run all my tests within WebStorm. I set up a project with Babel, TypeScript, and Vue using vue-cli 3.0.0-rc3. My run configuration looks like this: https://i.stack.imgur.com/7H0x3.png Unfortunately, I encountered the following error: ...

Creating a versatile TailwindCSS grid that can adjust to varying numbers of grid columns

I am currently working with Vue3 and TailwindCSS, attempting to create a grid using a dynamic grid-cols-{n} class. While I am aware that TailwindCSS typically supports up to 12 columns by default, the challenge arises when the number of columns needed is e ...

Using Vue.js to handle asynchronous functions with undefined variables

My Vue.js application is facing a problem where an async function is passing a variable as undefined even though it's properly defined before the function call. The async function FETCH_DATA in my Vue.js application is defined like this: async [FETCH ...

What is the best way to transfer variables to a different page through a pop-up window?

I'm working with a function that converts the Id of the clicked element into a variable, then opens a new window with a different page. How can I access or utilize this variable on the newly opened page? var idToWrite = []; $(function(){ $(".szl ...

How to eliminate spacing between slides in a 3D Carousel Slider using Bootstrap 5

My website utilizes Bootstrap along with a carousel slider, which is functioning properly. However, I am encountering an issue when the slider transitions from right to left. It briefly displays a white space between slides, which I wish to eliminate. I wa ...

Tips for converting asynchronous function calls into synchronous functions in Node.js or JavaScript?

Imagine you are managing a library that provides access to a function called getData. Users utilize this function to retrieve real data: var output = getData(); In the background, the data is stored in a file, so you have implemented the getData functi ...

Navigating the landscape of asynchronous asset loading can present challenges. Attempting to access assets immediately may result in receiving

I have encountered an issue while trying to load my assets into an array using a function called LoadJSON(). This function utilizes THREE.ObjectLoader() to load JSON files. The problem arises when I attempt to access the members of the array immediately af ...

Creating aesthetically pleasing URLs from data: A simple guide

Can someone help me transform this data into a pretty URL? I am looking for something similar to Appreciate the assistance! :) var x = {data1, data2, data3}; $.ajax({ url: 'https://mywebsite.com/admin/leads/count/', data: x, type: &a ...

Assigning a unique identifier to a button that will vary depending on the selected radio input

UPDATED HTML: The circumstances have changed because I am no longer in my office, but the concept remains unchanged. The situation is that on a certain part of a website, users have the option to choose from multiple saved addresses. Each address has a un ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

Utilizing dynamic router links with Angular

I am currently working with a list of strings in my application, using *ngFor to iterate through them without any issues. However, I have realized that the way I am handling indexes in ngFor to determine routes has some flaws, and now I want to make a chan ...

Retrieve the most recently added item in the Material-ui Autocomplete component

Currently, I am incorporating the material-ui Autocomplete component with multiple selection feature. In one specific scenario, I require the ability to retrieve only the value of a newly added item. Despite utilizing the onChange listener, the event pro ...

Updating Tailwind CSS to accommodate older web browsers by converting modern rgba() notation to be browser-compatible

I am facing a challenge with Tailwind CSS v3+ as it builds colors into the rgb space/color notation that is not compatible with an older browser (Safari 11) that my web app now needs to support. For example, rgb(163 160 158 / var(--tw-bg-opacity) The iss ...

The behavior of Mozilla in handling JQuery attr() function may result in variations in design elements such as font-family or font-size

I'm currently working on the login form. Below is my view in CodeIgnitor: <div id="login-form"> <?php echo heading('Login', 2); echo form_open('login/login_user'); echo form_input('email', set_value ...

In Angular, upon submitting the form, redirect to a separate component and display a message indicating the successful

I am facing an issue with a component that sends data to a service in order to save it in the database. Following this, I want to redirect or navigate to a different component and display a success message there. While I have implemented this functionality ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...

Django issue: A Tuple or struct_time argument is necessary

Currently, I am developing a code that deals with 2 variables - showdate and viewtype. Both of these variables are transferred via JavaScript using the POST method. viewtype = send an srt showdate = send a date from javascript Within this code snippet, ...

Could anyone lend a hand in ensuring that my AJAX call successfully processes the parameters?

When attempting to retrieve specific data from my database using AJAX, I encountered an issue where the call was successful when made through Postman or directly in the browser, but failed when initiated from my client. It seemed to work intermittently, re ...

We're sorry, the request was blocked due to a missing Access-Control-Allow-Origin header

Recently, while working on a blog application with the front end in react + typescript and backend in go iris, I encountered an issue when trying to fetch blog content using a get request. The backend was running on localhost:5000 and the node at localhost ...

Exposing the method to the outside world by making it public in

I have a situation where I have a base class with a protected method called foo, and a child class that needs to make this method publicly accessible. Since this method will be called frequently, I am looking for a more efficient solution to avoid unnecess ...