Combining Promise.all with multiple distinct data types for returned values

Can Promise.all() accept an iterable with different resolved types?

For example, can promise.all([promiseA, promiseB, promiseC]) work if promiseA and promiseB return void but promiseC returns boolean?

I attempted this and it seems not possible. I am unsure whether an iterable can have different types, so I wanted to confirm. The error I encountered is related to TypeScript in my code.

PromiseC: Promise<boolean>;
PromiseA: Promise<void>;
PromiseB: Promise<void>;

const promises = [this.promiseA, this.promiseB];
if (!flag) {
   promises.push(this.promiseC); 
}
Promise.all(promises).then(() => { // do something}

https://i.sstatic.net/cSCw1.png

Thank you for your help!

Answer №1

Absolutely, it is possible to utilize promises that return different types. The Promise.all(iterable) method, as explained in the MDN documentation, functions in the following way:

It provides a single Promise that resolves once all promises within the iterable have resolved or if there are no promises in the iterable. In case of rejection, it will reject with the reason from the first promise that rejects.

The resolved promise will contain:

... an array consisting of all values from the iterable provided as arguments (including non-promise values).

The output type is Array since any type can be stored in each element of a JavaScript array. This enables achieving the scenario you outlined. Below is a sample demonstration, with the console displaying undefined for two elements, along with a Number and a String type also present.

var p1 = new Promise((resolve, reject) => {
  resolve(console.log("Performing task...results in undefined akin to how a function behaves"))
})
var p2 = undefined;
var p4 = Promise.resolve(true)
var p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("foo");
  }, 100);
}); 

Promise.all([p1, p2, p3, p4]).then(values => { 
  console.log(values); // Array contains multiple types.
});

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

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

Is there a way to combine an onclick function with a return false statement within a submit button?

As far as I know, the default behavior when using return false is: <input type="submit" onclick="return false" /> However, in my current code, I want a submit button to trigger a different JavaScript function on click. This funct ...

Using AngularJS to hide elements within a nested dictionary structure

My dictionary structure is as follows: var data = { a: [1, 2, 3, 4, 5], b: [ [1, 2], [3, 4], [5, 6] ] }; Currently, I am using ng-hide to hide an element if the value 2 exists in data->a. Here's how it's implemented: <i ...

Experiencing an excessive amount of re-renders can lead to performance issues. React implements limits on the number of renders to avoid potential infinite

Would appreciate assistance in solving this code quandary. Whenever the "/" is removed before "about" and "id", it strangely does not generate any errors. import Navbar from "../components/Navbar"; import Footer from "../components/Footer& ...

Enabling the use of dot or full stop in JavaScript keycode for numeric input

I am facing a challenge with a method that is supposed to allow all numeric values, including the '.' symbol. Below is the code for my method. While it successfully allows numeric values, it seems to have an issue with keyCode == 190. function I ...

Is it possible to enable full screen window functionality in Angular 2 by simply clicking a button? Let's find out

After successfully creating the user login page, I am facing an issue. When the submit button is clicked, the page should navigate to a specific component (test.component.ts and test.component.html). My goal now is to make that window go into full screen m ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Retrieving an image from a JSON file based on its corresponding URL

I am trying to extract the URL and display it as an image: This is how it appears in JSON: https://i.sstatic.net/vpxPK.png This is my HTML code: <ul> <li *ngFor="let product of store.Products"> <p>Product Image: {{ product.Pr ...

An error occurred with useState and localStorage: the parameter type 'string null' cannot be assigned to a parameter of type 'string'

I am currently using NextJS and attempting to persist a state using localStorage. Here is my code implementation: const [reportFavorite, setReportFavorite] = useState([ 'captura', 'software', 'upload', ] as any) ...

Using Three.js to render an octahedron shape

I attempted to create an Octahedron shape, but the final result did not meet my expectations. I am unsure of the reason behind this. Instead, I now plan to draw a Dodecahedron. Any suggestions or advice on how to achieve this? Click here to view the outcom ...

Implementing Ajax functionality in MVC 3 to return a partial view

I wanted to express my gratitude for this invaluable site that has taught me so much. Currently, I am working on an MVC3 component where I need to populate a selectlist and upon user selection, load a partial view with the relevant data displayed. Everythi ...

Tips for concealing the delete button within the main content area and displaying it in the subsequent "add" pop-up window upon clicking the "add" button in Angular

I have a card with add and delete buttons. I want only the add button to show initially, and when clicked, a new card should open with both add and delete buttons. Everything is working as expected except I can't figure out how to hide the delete butt ...

What is the purpose of including window and undefined as parameters in this jQuery plugin?

Exploring the jquery resize plugin has left me puzzled about its inner workings: Typically, we only pass a jQuery object into jquery plugins like this: (function($){ ....plugin code.... })(jQuery); However, in the "resize" plugin, both window and un ...

Ways to troubleshoot the error message 't.rangeslider is not a function' in which rangeslider is a personalized function

I'm experiencing an issue with a function assigned to a variable that is throwing an error. Here is the code snippet: $(".sliderRange").each(function() { var t = $(this); t.rangeslider({ polyfill: !1, onSlide: function(e, a) { var n = ...

Utilizing Cordova and AngularJS to efficiently retrieve JSON data through XMLHttpRequest in a factory

I've encountered an issue while attempting to retrieve a JSON from an API using XMLHttpRequest within a factory. Despite the debug logs suggesting that everything is functioning correctly, I keep getting an "undefined" response. Below is the code for ...

Issues with connecting static files in express.js

Hey there! I'm having an issue with the redirect not working when I click the "Submit" button on the login page. The code in my index.js file looks like this: app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dir ...

Adjust the color of radio button text with Jquery

Here is a sample of radio buttons: <input type='radio' name='ans' value='0'> Apple <input type='radio' name='ans' value='1'> Banana <input type='radio' name='ans&apo ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...