What are the most effective techniques for utilizing promise.all in your codebase?

When trying to consolidate responses from two API calls in the code below, I'm facing an issue where Promise.all is not being invoked. Any suggestions on what might be implemented incorrectly and the best practice to achieve this using Promise.all?

The code snippet below follows the tsoa format and is written in TypeScript.

main.ts

   @Post("getStoreDetails")
   public async getStoreDetail(@Body() request: express.Request): Promise < any > {
       const stackurl = "http://staclurl"
       const storeurl = "http://storeurl"

       let stack;
       let store;

       if (request.body.lob === "Stack") {
           stack = await axios.post(stackurl, req.body).then(
               function(res) {
                   if (res.data.Header.StatusCode !== '0000') {
                       throw res.data.Header;
                   }
                   const Stackresponse = res.data.Details;
                   return Stackresponse;
               });
       }
       if (request.body.lob === "Admin") {
           store = await axios.post(storeurl, req.body).then(
               function(res) {
                   if (res.data.Header.StatusCode !== '0000') {
                       throw res.data.Header;
                   }
                   const StoreResponse = res.data.Details;
                   return StoreResponse;
               });
       }

       return Promise.all([stack, store]);

   }

Answer №1

By enclosing your stack and store within an if statement, they are no longer accessible in the outer function due to scope limitations. An alternative approach would be to utilize an array within the function scope to hold the two promises generated in the if statement. It's important to mention that removing the await keyword is necessary in order for these promises to be returned as objects that can be resolved by Promise.all

Answer №2

Your issue arises from a couple of factors:

  1. Using Promise.all when only one condition can be true
  2. Improper usage of the await keyword

The primary error is that request.body.lob can only contain one value, causing only one Promise to be returned within the if statement.

Another mistake is returning the resolved promise value instead of the promise itself due to using the await keyword.

You're actually returning the value of the promise in your stack and store variables, not the promises themselves. As a result, Promise.all cannot work as expected because there are no pending promises stored.

To resolve this, store the promise in the variables and handle the conditionals differently.

Answer №3

It appears that with just one request and a conditional statement, you can dynamically set the URL.

@Post("getStoreDetails")
public async getStoreDetail(@Body() request: express.Request): Promise < any > {

  const urls = {
    'Stack': "http://staclurl",
    'Admin': "http://storeurl"
  }

  const url = urls[request.body.lob];

  if (url) {
    return await axios.post(url, req.body).then(
      function(res) {
        if (res.data.Header.StatusCode !== '0000') {              
          throw res.data.Header;
        }    
        return res.data.Details;
      });
  } else {
    // What should be returned in case there is no matching URL?
  }

}

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

Which costs more, using an undefined ng-bind or both ng-bind and ng-show together?

Assuming that toShowVar is undefined, which of these options would be more costly? <span ng-bind="toShowVar" ng-show="toShowVar"></span> or <span ng-bind="toShowVar"></span> The latter option would clearly not display anything o ...

Tips for updating the background color when clicking in Vue

I've been attempting to change the background color of an element upon clicking it using Vue, but so far I haven't had any success. Here's what I have come up with, including a method that has two functions for the onclick event in Vue. &l ...

Experience the seamless integration of Restful APIs with AngularJS and Querystring parameters

I am currently in the process of developing a web application that includes edit functionality. Currently, I have created a page with a list of records, each containing an ID. When I click on the edit button, it triggers the following: $state.go ...

Page showing without banner

As I scroll down through my website, I want a specific banner to appear when I reach the contact page. The banner will show a goodbye message and give users the option to close it or keep it open. For example: (function() { requestAnimationFrame(fu ...

Is there a method to send a FontAwesomeIcon component as a prop to the ReactHTMLTableToExcel component?

When using ReactHTMLTableToExcel, you can set the prop buttonText as a String, <ReactHTMLTableToExcel id="test-table-xls-button" className="download-table-xls-button" table="table-to-xls" ...

Jquery JavaScript functions are compatible with Chrome and Firefox browsers but do not function properly in Internet Explorer

I am encountering an issue with my HTML file that includes CSS and Jquery. It works perfectly on Chrome and Firefox, but when tested on IE, only the CSS part functions while the JavaScript click function does not work at all. $(document).ready(function(){ ...

There seems to be a hitch in the functioning of the JavaScript codes

I'm having trouble calculating the amount using jQuery. Could someone please review my code and let me know what's wrong? Here are my Javascript and jQuery codes: After making changes: $(document).ready(function() { $('.home_banner&ap ...

Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge: I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core p ...

Chinese Input Causing Triggered Computed Problem in Vue 2

Currently working with vue2 on my development project. I have noticed that the computed property only activates when Chinese input is typed, either through keyup or keydown. (example: ㄨㄛˇ => 我 It only triggers once instead of three times when f ...

Tips for deleting a button from a DataTable file upload feature

I currently have Datatable set up to upload images using the code snippet below: { label: "Images:", name: "files[].id", type: "uploadMany", display: function ( fileId, counter ) { re ...

Progress bar in Angular that displays during all asynchronous operations in ngOnInit

In order to make users wait until all necessary data is retrieved, I would like to implement a progress bar using this library. The challenge lies in handling multiple HTTP requests and knowing when all calls have been completed so that the waiting bar ...

During the animation sequence, the element is seen ascending

I'm encountering a small issue with one of the elements I'm animating - it's moving up slightly during the animation process. It elevates about 2-3 pixels while the animation is playing, then snaps back down once it's completed. The el ...

Once more, objects cannot be used as a child element in React

I understand that there are similar questions about this topic, but I am struggling to approach it in a different way. I really need an array of objects to be inside a map. I have created an array to map it, but I need to find different information to disp ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...

Challenges with adjusting the value of HTML range inputs

Within my HTML, I have incorporated the following three elements: <button id="left" >Previous</button> <input id="animSlider" type="range" min="0" max="0" step="1" value="0" /> //THE MAX VALUE IS SET DYNAMICALLY UPON PAGE LOAD, NOT AS ZE ...

Combining multiple events in jQuery

It's fascinating to see that the two solutions provided are functioning correctly, but it seems like there might be an issue with the CSS I've written as the links do not appear when the hamburger button is pressed. Additionally, the background-c ...

Modify the background color of the entire page when the main div is clicked

I am attempting to alter the background color of my entire page when the div with id main is clicked. You can view the code here: $(document).ready(function() { var color = 1; $('#main').click(function(){ if (colo ...

Issue encountered in Ionic/React/Typescript - Incorrect props supplied to React.FC<'erroneous props provided here'>

Having struggled with this issue for a while now without any success, I have searched through numerous questions here but none seem to address my specific case. Therefore, I kindly request your assistance. I am encountering difficulties passing props thro ...

What is the method for handling JSON data in Node.JS?

I am working with a Node.JS file that includes the following code: var express = require('express'); var app = express(); var http = require('http').Server(app); var cfenv = require("cfenv"); var appEnv = cfenv.getAppEnv(); http.list ...

Can the ngx-chips library be used to alter the language of chips?

Currently, I am working with the ngx-chips library and encountering a particular issue. Here is an image representation of the problem: https://i.sstatic.net/GL3Fd.png The challenge I am facing involves updating the language of the chips based on the sele ...