Ensure that the promise is fulfilled only if a specific condition is met

I have a complex if-else condition in my code that includes different promises. Once the logic determines which condition to enter and executes the corresponding promise, I need to ensure that a final promise is always executed.

if (a < 5)
{
   vm.promise1()
   .then((data) => {
      //handle data
   })
}
else if (a > 5)
{
vm.promise2()
   .then((data) => {
      //handle data
   })
}
else
{
vm.promise3()
   .then((data) => {
      //handle data
   })
}

Now, I want to ensure that vm.finalPromise() is executed after any of the conditions are met. Is there a way to achieve this without having to use .finally() on each individual promise?

Thank you

Answer №1

If you ask me, I'd recommend sticking with a "Promisy" approach. Instead of directly storing a promise in a variable, consider calling a function that returns the promise. Keep in mind, this is simply a matter of personal style preference.

function doSomething() {
  if (a < 5) {
    return vm.promise1().then((data) => {
      //do something with data
    });
  } else if (a > 5) {
    return vm.promise2().then((data) => {
      //do something with data
    });
  } else {
    return vm.promise3().then((data) => {
      //do something with data
    });
  } 
}

doSomething().then(() => {
  // finally do something
});

Answer №2

To handle different promises, initialize a variable to store them

Simply use the variable as you would with any other promise following the if/else conditional code

var p;
if (a < 5) {
   p = vm.promise1()
   .then((data) => {
      //process data accordingly
   })
} else if (a > 5) {
    p = vm.promise2()
   .then((data) => {
      //process data accordingly
   })
} else {
    p = vm.promise3()
   .then((data) => {
      //process data accordingly
   })
}
p.then((result) => {
     //implement your logic here
});

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

When I test my jQuery scripts in jsfiddle, they run smoothly. However, they do not seem to work properly when I

My code is almost perfect, but the jQuery function is giving me trouble. It works fine in jsfiddle, but for some reason, it's not functioning in my HTML file. I don't believe extra characters are being added when copying from the HTML file. I hav ...

Error: Unable to execute $(...).stellar since it is not a recognized function

Having some trouble implementing the stellar plugin. I've included all the necessary js, but keep getting an error in the dev tools console: 'Uncaught TypeError: $(...).stellar is not a function'. Here's what I have in the head tags: ...

"Utilize jQuery to load a file when hovering over a specific

How can I dynamically load an external file using jQuery when a user hovers over a specific div? I attempted to load the file like a CSS file on hover but was unsuccessful. Is it possible to load a CSS file on hover as I've seen in some examples? $(d ...

Exploring numerical elements in interactive content

Struggling with the Wikipedia API and encountering issues with the results that are returned. {"query":{ "pages":{ "48636":{ "pageid":48636, Concerned about how to access a specific ID (such as 48636) without knowing it in advance ...

Encountering Webpack issues following the transition to Next 13

Since updating Next to version 13, we've encountered issues with our application not building properly. It appears that webpack is having trouble with imports, exports, and potentially typescript. ../../libs/queries/src/lib/groq/searchFaq.ts Module pa ...

Problem encountered while downloading dependencies with Snyk

While attempting to set up the dependencies for the W3C Respec project, I encountered this error message: npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for build steps and `pr ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

What is the importance of context in the subscription method of RxJS or Angular Observables?

In the given situations, I am providing a child Component with a property that is updated later through an RxJs Observable subscription. Angular fails to detect changes when not using an anonymous function or binding the this context. // Situation 1 // C ...

Using Three.js BVHLoader in React/React Native applications

I am currently working on developing an application or website for displaying BVH animation. I came across a BVHLoader example in Three.js that I found interesting: BVHLoader example. I am aware that React and React Native can be used with Three.js as we ...

CSS Class Not Updating in WordPress Using JavaScript

Looking to incorporate a small JavaScript code directly into The Twenty Sixteen theme in WordPress. This HTML Code needs to be modified on the Page: <p class="site-description">Example Text</p> The goal is to change a classname: document.g ...

Node React authentication

Struggling with implementing authentication in React Router. I am using componentDidMount to check if the user is logged in by calling an endpoint. If not, it should redirect to login, otherwise proceed to the desired component. However, this setup doesn&a ...

jQuery AJAX issues on Safari and iOS gadgets

I'm facing a compatibility issue specifically with Safari and all iOS devices. I've developed this jQuery code for a project, but it seems to have trouble working with Safari. Interestingly, it works perfectly fine with Chrome, Firefox, and even ...

Determine the Availability of a URL with AngularJS

Looking for a way to verify the existence of a URL like www.testsite.com/mypage using AngularJS. Is this possible? Any suggestions from the community? ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

Automating the deployment of a vue.js app using GitLab CI/CD pipeline to deploy to

Currently experiencing an issue with the pipelines involving my YAML file that automates deployment of a Vue app to Firebase. Despite including scripts in the file and setting up the Environment variable FIREBASE_TOKEN on GitLab, pushing the code to a GitL ...

The result should display the top 5 application names based on the count property found within the ImageDetails object

data = { "ImageDetails": [ { "application": "unknownApp, "count": 107757, }, { "application": "app6", "count": 1900, }, { & ...

Console shows successful jQuery ajax request, but the callback function is not being executed

I've been working on a jQuery POST request that's been giving me some trouble. Here is a snippet of the code I'm using: $.ajax("/myurl",{ data:{ ... }, mimeType:"application/json", dataType:"application/json", me ...

Are you delving into the realm of reduce functions in order to grasp the intric

Currently following this particular tutorial where they utilize the reduce method to transform an Array<Student> into a { [key: string]: Array<string | number> }. The tutorial includes this expression that caught my attention. It's quite n ...

Launching event handlers and applying CSS classes within a single scenario

How can I toggle the visibility of a button based on form field validation in JavaScript? I want to show or hide the button when the .confirm button is clicked, and if the form is valid, add a checkmark to the body element through event listener. The issu ...

Jest does not support util.promisify(setTimeout) functionality

While I understand there may be similar questions on SO, I believe mine is unique and hasn't been addressed in the current answers. I'm currently experimenting with testing a REST API in Express.JS. Below, you'll find a basic working exampl ...