Completing the initial task before moving on to the next task: Leveraging Ionic 2 Promises

Currently in my Ionic 2 project, I am facing an issue where two functions are executing one after another but the second function starts before the first one is completed. Both functions involve making API calls and I want to ensure that the first function finishes its execution entirely before moving on to the second function.

To address this issue, I have been advised to use Promises. I have simplified the code for better readability:

const first = () => {
  self.pspService.post('/api/Conversation/GetPersonalCalendarData',
    {
    }, result => {
      result.Data.forEach(lAppointment => {
        // logic here
      });
    });

  return new Promise((resolve, reject) => {
    resolve();
  });

};

const second = () => {
  self.pspService.post('/api/Conversation/AddPersonalAppointment', {
  }, result => {
    // logic here
  });

  return new Promise((resolve, reject) => {
    resolve();
  });
};

first().then(() => {
  return second();
});

Answer №1

If you want to encapsulate your post within a new Promise, here is how you can do it:

const initiate = () => {
    return new Promise((resolve, reject) => {
        self.pspService.post('/api/Conversation/GetPersonalCalendarData', {
            }, result => {
                result.Data.forEach(lAppointment => {});
                resolve();
            });
    });

};

const execute = () => {
return new Promise((resolve, reject) => {
    self.pspService.post('/api/Conversation/AddPersonalAppointment', {
        }, result => {
            resolve();
        });
});
};

initiate().then(() => {
     return execute();
});

Alternatively, you could also directly return the promise created by the POST request:

const initiate = () => {
    return self.pspService.post('url, {}, result => {
            result.Data.forEach(lAppointment => {});
            return Promise.resolve(result);
        })
}

Answer №2

Utilize the updated HttpClient along with switchMap in order to retrieve a distinct Observable

fetchData(){
    return self.dataService.fetchData('/api/Conversation/RetrieveUserData')
          .switchMap((result:any)=>{
            //once you have the "result", you can modify the data
            return self.dataService.post('/api/Conversation/AddUserAppointment')
           });
}
//Within your component
myService.fetchData().subscribe((appointmentData)=>{
    //appointmentData represents the result of self.dataService.post
}

Answer №3

If you encounter situations like this, remember that async/await can be used to manage them effectively. Asynchronous functions are identified by the async keyword; await halts the execution until a promise from an asynchronous function is fulfilled and extracts the value from the returned Promise.

async func(){
    const first = () => {
      self.pspService.post('/api/Conversation/GetPersonalCalendarData',
        {
        }, result => {
          result.Data.forEach(lAppointment => {
          });
        });

      return new Promise((resolve, reject) => {
        resolve();
      });

    };

    const second = () => {
      self.pspService.post('/api/Conversation/AddPersonalAppointment', {
      }, result => {

      });

      return new Promise((resolve, reject) => {
        resolve();
      });
    };

    let firstValue = await first();
    console.log("First Value", firstValue);
    let secondValue = await second();
    console.log("Second Value", secondValue);
  }

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

Styling a specific row in Angular application

In my Angular application code, I am trying to iterate through the tr elements and apply styles to specific rows. There would be multiple rows needing this treatment. For example: <tbody> <tr *ngFor="let row of fsIncomeStatementTable | ...

When testing, the @Input() variable that is inherited and initialized in the child constructor will be null during ngOnInit

I am currently working on testing Angular components using jest. I encountered an issue where a component initializes a variable in its constructor that becomes null during ngOnInit when the component is tested, but remains as expected when the application ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

Troubleshooting form submission issues in Angular 4

I am encountering a few issues with my search form. It is supposed to function as a search tool with one input field and one button. However, something seems amiss. I am utilizing an API that returns values based on the string inputted. When an empty value ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...

There are no code completion suggestions available for MUI v5 types when using WebStorm

Why am I not receiving code completion suggestions for MUI components in WebStorm? TypeScript v4.4.4 WebStorm 2021.2.3 MUI v5.0.4 function App() { const { path, url } = useRouteMatch(); return ( <div className="App"> &l ...

Angular Unit Test: Received 1 argument instead of the expected 3

Currently, I am in the process of unit testing an Angular application. This is my first time venturing into Angular Unit Testing. To save time, I downloaded the angular app from here. As a beginner in Unit Testing, I watched some informative videos on the ...

What purpose does the declaration section serve within the app.module file in Angular?

declarations: [ HomeComponent, DashboardComponent, ProfileComponent ], bootstrap: [ HomeComponent ] }) ...

What's the significance of & in TypeScript and JavaScript?

While exploring someone else's code, I came across this interesting piece related to the props of a React component. Although I'm aware that & is typically used as an AND logical operator, it seems to have a different significance in this con ...

Issues with Angular 9 routerLinkActive functionality causing unexpected behavior

Whenever I navigate to a different router link, the previous link remains active, resulting in multiple active links with the same class. <div class="side-link" [routerLink]="['/']" [routerLinkActive] = "['link-active']">Dashboar ...

I need to save the API response in object form from Angular so that I can use it later. Can someone suggest the best way to store this response efficiently?

Angular: I need to find a way to save the API response, which is in object format, for future use and to reduce additional API requests. Can someone suggest a convenient method to handle this? Snippet of My Code (Service File): getList(){ .... .... ...

How can I incorporate a callback function into Typescript when using Angular Material?

I am utilizing the Angular Material Dialog component and aiming to include an optional callback function, which will be triggered upon the user clicking the OK button. Can anyone guide me on how to achieve this? askUser(customData: any) { openDialog() ...

Storing a value received from an observable into a component variable in Angular 4 using the subscribe method

I am attempting to save the value from an observable into a variable within the component by utilizing a service. However, the variable always ends up as undefined. When I check "names" inside the subscribe function, it does contain the expected value. ...

How can I ensure that all the text is always in lowercase in my Angular project?

Is there a way to ensure that when a user enters text into an input field to search for a chip, the text is always converted to lowercase before being processed? Currently, it seems possible for a user to create multiple chips with variations in capitaliza ...

A guide to writing a script to access and return a specific element stored in an array within an object's property

I have created this specific function function extractSingleValue<T, TElem, K extends keyof T>(obj: T, name: K): TElem { const source = obj[name]; if (source.length !== 1) { throw Error(`There should be exactly one ${name} associated`); } ...

encountering an error of unsupported grant type while attempting to authenticate a user

I've seen a lot of discussions on this topic, but none have addressed my specific issue. Currently, I am working on an angular 5 application and trying to retrieve an authentication token by sending a post request to a server. Testing the connection ...

Uninitialized Array Member in Angular 8

Can anyone explain why the code snippet below is printing "undefined"? I have created several objects and intended to display the corresponding images, but after iterating through them using ngfor, nothing appeared. To investigate, I logged the array and ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Developing an interface that utilizes the values of an enum as keys

Imagine having an enum called status export enum status { PENDING = 'pending', SUCCESS = 'success', FAIL = 'fail' } This enum is used in multiple places and should not be easily replaced. However, other developers migh ...

HTML set hover & active states to remain active indefinitely

NOTE: My project utilizes Angular, so Angular may offer a solution to this issue as well I am in the process of creating a page where I can preview and test out various styles that I have designed. In order to achieve this, I need to somehow activate both ...