Order of execution not maintained while running Javascript Promise and Then with Http Services

My current approach involves using a Promise along with a then() method to execute some code asynchronously. The objective is to have the addTimeToTimecard() function trigger another function with an HTTP request within it once the promise resolves, followed by executing a second HTTP service in the then() block.

addTimeToTimecard() {

const promise = new Promise((resolve, reject) => {
  this.checkAndCreateTimecard();
  resolve();
});

// Ensure that everything in the function above completes before proceeding with the upcoming HTTP request
promise.then(() => {
console.log("do the patch")

 this.httpService.patch('setTimeIn/', { timeVar: "TimeIn", timeAmount: this.time1 }).subscribe()

})

  checkAndCreateTimecard() {
    this.httpService.get('timecard/fullTimecard/' + this.workDate).subscribe((ft: any) => {
      console.log("got the timecard")
  )}
 }

//output:
do the patch
ERROR timecard doesn't exist
got the timecard

I've been relying on SetTimeout() for such scenarios, but I understand that using Promises or async/await would be more appropriate. Can you help identify my mistake here and suggest best practices for working with promises?

Answer №1

If you're utilizing Angular, it would be more beneficial to consolidate requests using the switchMap operator:

addTimeToTimecard() {
  return this.checkAndCreateTimecard()
    .pipe(switchMap(data => {
      return this.httpService.patch("setTimeIn/", { timeVar: "TimeIn", timeAmount: this.time1 });
    });
}

checkAndCreateTimecard() {
  return this.httpService.get("timecard/fullTimecard/" + this.workDate);
}

Alternatively, if you prefer using promises for some reason, consider the [toPromise operator] (https://www.learnrxjs.io/learn-rxjs/operators/utility/topromise) as a solution.

addTimeToTimecard() {
  return this.checkAndCreateTimecard()
    .then(data => {
      return this.httpService.patch("setTimeIn/", { timeVar: "TimeIn", timeAmount: this.time1 }).toPromise();
    })
}

checkAndCreateTimecard() {
  return this.httpService.get("timecard/fullTimecard/" + this.workDate).toPromise();
}

On a side note, sticking with Observables is my recommendation.

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

Encountering an Issue: Unable to connect with 'ngModel' as it is not recognized as a valid property for 'input' even after importing FormsModule

Despite importing FormsModule in my app.module.ts, I am still encountering the following error message. 'Cannot bind to 'ngModel' since it isn't a known property of 'input' I have thoroughly reviewed similar posts, but unf ...

Guide on importing a client-side script using browserify with module.exports exposed through jadeify

I've successfully created a JavaScript file using a Jade template with the help of browserify, browserify-middleware, and jadeify on the server side in Node. The only thing required to generate the JavaScript file is: app.use('/templates', ...

Determining the orientation of an image in JavaScript

Currently, I am attempting to determine the orientation of images using JavaScript in order to apply a specific class to them. This process seems to be functioning correctly on Firefox, but is presenting challenges on other browsers. It appears to work bet ...

Difficulties in Configuring Testacular Integration with Jasmine and Angular

I'm in the process of setting up a unit testing environment for my project and encountering some difficulties. Specifically, I am attempting to utilize Testacular with Jasmine to test my AngularJS code. One of the challenges I am facing involves a mo ...

Toggle the opening and closing of React components with a map function using onclick

Implementing an onClick function within a map operation, I am encountering an issue where clicking the onClick button changes the state of all items in the map, instead of just the item clicked. This is being done using the useState hook. const [open, se ...

Restrict input to only text characters in a textbox using AngularJS

Looking for a way to ensure that users can only input characters into a textbox in my project. Any suggestions on how I can accomplish this? ...

What is a different approach in Angular that can be used instead of the href attribute found in

I am trying to define a constant URL in my component.ts file so that I can test it and use it in my HTML file. I have tried using ngHref but it's not working in my case. How can I successfully define a constant URL in my component.ts file and access i ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...

TypeScript's TypeGuard wandering aimlessly within the enumerator

I'm puzzled by the fact that filter.formatter (in the penultimate line) is showing as undefined even though I have already confirmed its existence: type Filter = { formatter?: { index: number, func: (value: string) => void ...

Tips on adding a tooltip to the react-bootstrap tab element

How can I add a tooltip to the tabs in my React application using Bootstrap tabs? I have three tabs and I want a tooltip to appear when hovering over each tab. import { Tabs,Tab} from "react-bootstrap"; // inside return <Tabs variant="pills" ...

Dirty context detected in Material-UI TextField

Trying to understand how to check for dirtyness with material-ui's FormControl or TextField component. The TextField demo page mentions that TextField is made up of smaller components (FormControl, InputLabel, Input, and FormHelperText) which can be c ...

Three fixed position divs arranged horizontally side by side

I am attempting to organize 3 divs in a row using Flex. ISSUE 1: The div that is centered is set with position: fixed. However, the two other divs on each side do not stay aligned with the centered fixed div when scrolling. If I change the centered div to ...

How to customize the width of each table cell (td) in Angular 2 grid view

How can I set the width of each "table->thead->td" in grid view when getting head elements from an array? I am struggling to figure out how to adjust the width for each tr. Can anyone offer assistance with this Table column issue? private channels ...

Guide to incorporating Bootstrap 3 and Bootstrap 4 in a single Angular CLI project

Looking for guidance on how to integrate Bootstrap 3 and Bootstrap 4 into a single Angular CLI project. Any tips or advice would be greatly appreciated! ...

Incorporating EJS Statements in a Simple HTML Document along with TypeScript

Trying to comprehend a seed project for Angular 2 which is quite complex, something caught my attention in the index.html file that I can't explain. There seems to be ejs statements included: <!-- src/client/index.html --> <title><%= A ...

Obtaining the created by and modified by values from a SharePoint list can be achieved using Angular's http get method

I have received a response that includes the Created date and Modified date, but the Created by and Modified by information is missing. this.http.get(this.baseurl + "_api/web/lists/getByTitle('mylist')/items?$select ID,Created,CreatedBy, ...

Encountered issues while trying to utilize wasm function within Vue framework

When attempting to integrate wasm with Vue, I encountered a frustrating issue where the startQuorum function in my wasm file could not be located. import { Go } from './wasm_exec' import quorumWasmUrl from './lib.wasm' export const sta ...

Angular, delete any item from the scope that has a matching key value

One of the challenges I am facing is removing items from an array with the same key value of skillId when a button in the repeat is clicked. Here's the code snippet I have worked on: $scope.deleteSkill = function(skill) { for (var i=0; i<$ ...

Guide on how to set a custom image as the cursor when clicking on an image through javascript

Does anyone know how to use javascript to change the cursor to a custom image by updating the cursor property of the entire page? I'm getting an error in the Chrome console that says: projetFinalPage1.html:626 Uncaught TypeError: Cannot read property ...

"Upon initializing the page, Angular Material select remains enabled instead of being disabled

Incorporating parent and child select lists in Angular 18 with Angular Material 18 has presented a challenge for me. My goal is to have the initial parent option set as "Show all," which should then disable the child select list. However, if the parent val ...