What is the best way to combine a Promise.all with additional Promises?

I need to order the execution of my code as follows:

  1. Promise 1
  2. Wait for 1 to finish, then run Promises 2 and 3 simultaneously
  3. The final function should wait for Promises 2 and 3 to complete

I'm struggling to figure it out, and here is the code I have so far.

function getPromise1() {
  return new Promise((resolve, reject) => {
    // do something asynchronously
    resolve('myResult');
  });
}

function getPromise2() {
  return new Promise((resolve, reject) => {
    // do something asynchronously
    resolve('myResult');
  });
}

function getPromise3() {
  return new Promise((resolve, reject) => {
    // do something asynchronously
    resolve('myResult');
  });
}

getPromise1()
.then(() =>
  Promise.all([getPromise2(), getPromise3()])
)
.then(() => console.log('Finished!'));

Answer №1

Instead of using individual promises, combine them using Promise.all(...

fetchData1().then(() => {
  return Promise.all([fetchData2(), fetchData3()]);
}).then((data) => console.log(data)); // data from source 2 and 3

Answer №2

Even though this discussion is from a while ago, I feel like

() => {return Promise.all([getPromise2(), getPromise3()]);}

might be a bit unnecessary. The beauty of the fat arrow function is that you can simplify it to:

() => Promise.all([getPromise2(), getPromise3()])

which can make the code easier to understand:

getPromise1().then(() => Promise.all([getPromise2(), getPromise3()]))
.then((args) => console.log(args)); // result from promises 2 and 3

But regardless, I appreciate the insight provided. It really helped me out of a rut :)

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 jqGrid colModel is failing to execute a function as expected

Within the given code snippet, the function attrSetting is invoked. However, when I modify it to {"name":"A", "index":"0", "cellattr":attrSetting}, the code executes smoothly. But here lies the issue - cellattr interprets it as a string rather than a fun ...

Create a Buffer that includes all the characters of the alphabet when converted to

My current project involves using Node.js to generate secure, random tokens. Here is a snippet of the code I'm using: crypto.randomBytes(32).toString("hex"); // dd89d6ab1a7196e8797c2da0da0208a5d171465a9d8e918d3b138f08af3e1852 Although this method wo ...

Having trouble retrieving the pathname of a nested route within middleware.js in next js version 14

I am currently referring to the official App Router documentation for Authentication on this page My goal is to extract the pathname from the next URL export function middleware(request) { console.log('now we are in middleware'); const { ...

Utilize JavaScript objects to convert subscripts into HTML elements

I am currently developing an Angular 1X application where all icon labels are stored in a JS object as shown below: var labels={ ........ iconlabel_o2:"O<sub>2</sub>", iconLabel_co2:"CO<sub>2</sub>", iconLabel_h20:"H<sub ...

Does the organization of files and directories (such as modular programming) impact the speed at which AngularJS loads?

Can breaking code into smaller modules help decrease loading time? Exploring ways to modularize AngularJS applications can lead to a well-structured approach for developing large apps. This approach aims to streamline the development process by organizing ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...

What is the correct way to outline the parameters for deactivating functions?

Request for Assistance! I am facing a challenge with multiple blocks in my WordPress website. Each block contains a checkbox, two select options, and an element that needs to be toggled based on the selected options in the dropdowns. The functionality to ...

Showing and hiding nested Form Group validation in Angular 4 is a crucial feature that can improve

I have been exploring Angular 4 validation recently. Currently, I am working with a reactive form that contains two radio buttons and two form groups. The behavior I'm trying to achieve is when the user selects the first radio button, it removes valid ...

Discover the position of characters within a given string

I'm trying to accomplish a task similar to this: If the array [ "a", "b", "c" ] includes any of the characters in the constant word = "abracadabra", I want to retrieve that character along with its position in const word. My attempt so far looks lik ...

Toggle the status of active to inactive instantaneously with the click of a

Incorporating DataTables with ajax using PHP CodeIgniter Framework has presented me with a challenge. I am struggling to toggle between Active and Inactive buttons seamlessly. My desired outcome: When the Active button is clicked, it should transition ...

I'm confused as to why my React application is showing a blank screen even though I successfully imported and used an icon from Material UI. It compiled without any errors

I encountered an issue with my code when I added the "Avatar" line. To fix the problem of material UI not displaying properly, I had to use react icons instead. If possible, I would like recommendations for alternative packages that include the Avatar co ...

javascript making a button using an object

When trying to create a button from a JavaScript object, I am following this approach: for (buttonName in buttons){ var htmlbutton = '<button type="button" onclick="'+buttons[buttonName]()+'">'+buttonName+'< ...

Leveraging Handlebars for templating in Node.js to incorporate a customized layout

app.js const exphbs = require('express-handlebars'); app.engine('handlebars', exphbs({defaultLayout: 'layout'})); app.set('view engine', 'handlebars'); app.use('/catalog', require('./routes/ ...

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...

Detecting browser or tab closure in Node/Express Application: A comprehensive guide

As I'm developing a Node + Express MVC application, I am looking for a way to automatically shut down the Express server when the browser or tab is closed. While I know I can achieve this using a vanilla JS script with the 'beforeunload' eve ...

For optimal display on mobile devices, include "width=device-width" in the meta tag "viewport"

Is it necessary to include "width=device-width" in the meta tag named viewport when dealing with mobile phones? I've been attempting to make use of this, but without success: //iPhone Fix jQuery(document).ready(function(){ if (jQuery(window).widt ...

Connecting a specific entry in a data table with a corresponding web address

I have been working on a vue component that utilizes vue-tables-2. You can find the functioning example here. My goal is to link the edit href url to the entire row rather than just the edit cell. I attempted to achieve this using vanilla javascript by a ...

What is the correct way to utilize preloads and window.api calls in Electron?

I am struggling with implementing a render.js file to handle "api" calls from the JavaScript of the rendered HTML page. The new BrowserWindow function in main.js includes: webPreferences: { nodeIntegration: false, // default value after Electr ...

KnockoutJS - Struggling to bind model from simple JSON array

I've been working on an application that relies on a static JSON array, without the support of a backend service. I've been attempting to bind this JSON array to the page using KnockoutJS. Although I can successfully load the JSON array and creat ...

Using res.sendfile in a Node Express server and sending additional data along with the file

Can a Node.JS application redirect to an HTML file using the res.sendFile method from express and include JSON data in the process? ...