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

The data is not appearing in the Vuetify data table

I have encountered an issue with the Vuetify data table where it is not displaying any data. Even though it shows that there is 1 row out of 1 displayed, the table body remains empty. Below is my component code: <template> <v-data-table :hea ...

Moving the Promise.all feature from AngularJs to VueJs

I'm currently facing a challenge with moving a function from AngularJs to VueJs. I would really appreciate any help or suggestions you may have! items = { one: {...details here...}, two: {}, } In AngularJs: var promises = []; var deferred = $ ...

Issue with a variable within an *.ejs file

Currently, I am following a guide found at this link, and everything is working smoothly except when I encounter an error on the login screen: ..... 7| >> 8| <% if (message != null) { %> 9| <%= message %> 10| <% } %> 11| message is not defined ...

Obtaining data from the following entry in JSON format using the Twitter API

I am currently developing a webpage that showcases user tweets, however I want to visually represent the gap in time between each tweet by displaying empty spaces. I have been struggling with the logic of how to achieve this task and haven't made muc ...

Finally, $.getJSON has been triggered

When I click on an element, I want to open a bootstrap modal. The modal contains values retrieved from an ajax call using getJSON. However, the issue is that the getJSON function is only called after the jQuery function has finished executing. Below is my ...

jQuery problem: Unable to access a property that is undefined

After testing my code on JSfiddle, I noticed that it works perfectly. However, when I try to implement it on a webpage with jQuery already loaded in the DOM, I encounter a console error, shown in the screenshot. I am certain that the iframe selector I am ...

Please provide several input fields with identical 'name' attributes for submission

I'm encountering an issue with a form where multiple input fields (text) share the same name attribute. On the backend, I am utilizing node.js and Mongoose for a POST method. Below is a snippet of the code: if(existingFruit) { Fruit.findOneA ...

What causes a globally declared array to remain empty in the global scope even after data is pushed to it within a callback function?

Initially, I set an empty array as the value for the global variable artistURLs. Then, within the Cheerio .each() iterator method, I push strings (stored in the local variable artistURL) into the artistURLs array. var request = require('request&apos ...

What is the reason behind the lack of asynchronous functionality in the mongoose find method

Outdated code utilizing promises I have some legacy code implemented with mongoose that retrieves data from the database. The schema being accessed is AccountViewPermission. Everything works fine as I am using a .then, which essentially turns it into a Pr ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

Is it possible to manually activate a dropdown event using pure JavaScript?

I am attempting to manually trigger a dropdown event using JavaScript. Below is the function where I am trying to achieve this. I have successfully halted the initial event that occurs and now I need to initiate a dropdown event. stopNavigationTriggerDrop ...

A new sub-schema has been created in the JSON schema specifically tailored to a certain property

I needed to create a JSON schema with 3 fields: num, key1, and key2. The fields num and key1 are required, while the field key2 is only mandatory if key1 has a value of 'abc'. Below is the schema structure I came up with: schema = { type: &ap ...

AngularJS iOS keyboard not disappearing post iOS 10 update

After updating my device to iOS 10, I encountered an issue with hiding the iOS keypad when switching from one view to another. This functionality was working perfectly fine on iOS 9.3. Previously, I had programmed it to intercept certain elements and auto ...

Step-by-step guide on creating a monochrome version of an image using automation

In WordPress, I have a logo parade where all logos are in color RGB. I really like the effect of having them appear as black and white initially and then transitioning to color when hovered over. I am familiar with using sprites for this effect, but it wo ...

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Using ngrx to automatically update data upon subscription

Background The technology stack I am using for my application includes Angular 4.x, ngrx 4.x, and rxjs 5.4.x. Data is retrieved from a websocket as well as a RESTful API in order to share it between multiple components through ngrx. Currently, data is ref ...

Generate an array using hyperlinks within a list item created by the user

In the process of developing a program, I have included a feature where users can drag and drop .wav files into a playlist-container. These files are then played in the order they are arranged within the playlist-container. Currently, I am working on imple ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

What is the reason javascript struggles to locate and replace strings with spaces in a URL?

Let me begin by sharing the code I'm currently working on so that you can easily follow my explanations. Apologies for the French language used, as this website is being developed for a French-speaking school. I have eliminated irrelevant sections fro ...

Utilize jQuery and JavaScript dynamically in an HTML document on iOS devices

Having some trouble with this code snippet and getting it to work as intended. - (void)viewDidLoad { [super viewDidLoad]; _webview.delegate = self; [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBun ...