What is the best way to transfer a variable to a Promise.all operation?

In the scenario presented, there is an attempt to pass the constant filter into the Promise.all function, but the method of passing it down is proving to be a challenge, resulting in it being undefined in the final line of code.

What is the best way to pass the variable into the Promise.all function?

if (query.filter) {
  const dynamicFilter = '&filter=' + query.filter;
} else {
  const dynamicFilter = '';
}

const [companyResponse, requestsResponse] = await Promise.all([
  // Performing an API Call to "Read a company"
  $axios.$get('/companies/' + params.company),

  // Performing an API Call to "List a company's requests"
  $axios.$get('/companies/' + params.company + '/requests?count=5&include=owner' + dynamicFilter)
]);

Answer №1

const is localized to blocks. Therefore, the variable filter is actually undefined outside of the if statements. See the mistake in the following code snippet:

const query = { filter: '' }

if (query.filter) {
  const filter = '&filter=' + query.filter;
} else {
  const filter = '';
}

console.log(filter)

To rectify this issue, you need to declare filter outside of the block scope, which can be done with const by using a ternary operator in this scenario:

const filter = query.filter ? `&filter=${query.filter}` : '';

const [companyResponse, requestsResponse] = await Promise.all([
  // API Call "Read a company"
  $axios.$get('/companies/' + params.company),

  // API Call "List a companies requests"
  $axios.$get('/companies/' + params.company + '/requests?count=5&include=owner' + filter)
]);

Answer №2

The reason behind the error is that the filter was defined within an if statement. The solution is to define it before the if statement:

let filter

After making this change, you can remove the "const" keyword from both the if and else blocks.

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

Partial data is being received from the Ajax call

I currently have a textarea and a button on my webpage <textarea id="xxx" class="myTextArea" name="Text1" cols="40" rows="15">@ViewData["translation"]</textarea> <input type="button" id="convert-btn" class="btn btn-primary" value="Convert t ...

Divide the string by spaces

One of the challenges I am facing involves a textarea where users can input messages. The goal is to split the message into an array of words after detecting an '@' symbol, and then search for specific words in that array such as @person1 and @pe ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

Unable to retrieve scripts upon returning to the main page of a Jquery website

Starting fresh with this post, I'm feeling incredibly frustrated and close to giving up on JQM completely. This shouldn't be so difficult. Here's my website structure: OUI/ index.php js/ pages/ images/ On the index.php page at http://loca ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...

Using Laravel along with Inertia.js and Vue, we can easily determine whether a user is logged in

I am currently using Laravel along with Inertia.js for my project implementation. I am facing an issue where I want to display a div element containing some user details in the navbar only if the user is logged in. However, the div should not appear if the ...

How to display a PDF file stored in the documents directory of an iOS device with Phonegap

I'm encountering an issue when it comes to displaying a PDF using HTML, PhoneGap, or JavaScript. The web application I'm working on is developed in Sencha Touch 2. Here's exactly what I need: I need to display a PDF file located in the d ...

How can we restrict the text within a child div to a specific number of characters based on the size of the parent div?

So, imagine your HTML elements arranged as follows: <div class="Main"> <div class="About_Sports"> <div class="sportsPhoto"> <div class="content"> <di ...

Creating a streamlined Vue template rendering experience, free from any unnecessary clutter

I have developed a basic set of Vue components that are currently working well with an existing C# application. Currently, these components are stored as .html files (imported into the app using <script> tags) and .js files loaded by reference. All ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Steps to incorporate / insert Angular directive in an application

In my app, the main.js file is located in the root folder. -app |_ routes.js |_ main.js -components |_directives |_abc-directive.js I am trying to figure out how to define a directive that can be accessed from a different folder. This is what I at ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

Troubleshooting an issue when trying to call a PHP function in jQuery Ajax that is

Having trouble with include statements in my PHP files. When the page loads initially and then gets loaded again through jQuery ajax calls, I encounter an error with my include statements. I have a main page that includes a PHP script like this: <div i ...

Receiving a JSON object in response after sending data to a server using JavaScript

I am facing an issue with passing an email and password on login click to a database using PHP. After testing the email and password combination, PHP sends back a JSON object. While I have verified that the PHP code is functioning correctly and returns a J ...

"The Ajax POST request to MyUrl returned a 404 error, indicating that the resource

While working on my Grails code, I encountered an error when the Ajax function received a response from the controller action. The parameters are being passed successfully by the Ajax function, and the controller function is executed. However, upon return ...

Guide to dynamically using array.map based on a condition in React

I am encountering an issue with a modal screen that contains two dropdowns and a text input field. The problem arises when the second dropdown is set to “is empty”, as the text input field should then disappear, leaving just the two dropdown inputs on ...

Page redirects automatically after AJAX call

I'm a beginner when it comes to using AJAX and I am trying to delete a student from a list through an AJAX request. I want the response of the request to be displayed on the same page within a specific div, but instead, the response keeps redirecting ...

Unveil Secret Divs with a Click

I am in search of a way to display a hidden div when I click on a specific div, similar to the expanding images feature in Google's image search results. I have made progress with my limited knowledge of javascript, as shown in this CodePen: http://co ...

What is the method for verifying authentication status on a Next.js page?

I'm struggling to understand why the call to auth.currentUser in the code snippet below always returns null. Interestingly, I have another component that can detect when a user is logged in correctly. import { auth } from "../lib/firebase"; ...