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?