Promise.all is not functioning as expected

I need to make multiple asynchronous calls before my final call, and I came across a solution similar to this one on Stack Overflow.

Check out the code in this CodePen

class Person {
  name: string;
  constructor(init){
    this.name = init;
  }
}
let people: Person[] = [];
let names:string[] = ['janes','james','jo','john','josh'];
names.forEach(n=>people.push(new Person(n)));
function printName(name:string) {
  let getSomething = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(name);  
    },1000)
  });
  getSomething.then(function(){
    console.log(name);
  });
}
/// main
let request = [];
console.log('start');
people.forEach(person => { 
  request.push(printName(person.name));
})
Promise.all(request).then(result=> {
  console.log(result);
  console.log("finsh");
})

The output of the above code:

"start"
[undefined, undefined, undefined, undefined, undefined]
"finsh"
"janes"
"james"
"jo"
"john"
"josh"

what I expect it to be:

"start"
"janes"
"james"
"jo"
"john"
"josh"
[undefined, undefined, undefined, undefined, undefined]
"finsh"

Answer №1

Ensure that you are properly returning the promises created in printName to the request array. If not, when calling Promise.all, it will be on an array of undefineds and will resolve immediately. To avoid this, make sure to chain and return the promises.

When using Promise.all, it is common to want the resolved array to contain actual values rather than undefineds. To achieve this, also ensure you return the name inside the getSomething.then so that Promise.all resolves with an array of names:

function printName(name:string) {
  let getSomething = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(name);  
    },1000)
  });
  return getSomething.then(function(){
    console.log(name);
    return name; // include this line
  });
}

Here's a functional code snippet in regular JavaScript:

class Person {
  constructor(init){
    this.name = init;
  }
}

let people = [];
let names = ['janes','james','jo','john','josh'];
names.forEach(n=>people.push(new Person(n)));

function printName(name) {
  let getSomething = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(name);  
    },1000)
  });
    return getSomething.then(function(){
      console.log(name);
      return name;
    });
}
let request = [];
console.log('start');
people.forEach(person => { 
  request.push(printName(person.name));
})
Promise.all(request).then(result=> {
  console.log(result);
  console.log("finish");
})

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

Troubleshooting data binding issues with bootstrap tab panes and accordion components

Initially, I set up a bootstrap accordion that generates panels based on items with the property "gebieden". This functionality is functioning correctly. Within each panel, I implemented bootstrap 'tabs'. For every object with properties "onderw ...

What is the process for fetching the chosen outcome from a subsequent webpage using HTML?

How can I display selected cities on a different webpage after clicking a button? Currently, I can only get the results on the same page. For example, if a user selects NYC and Delhi, those cities should be displayed on another HTML page. ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...

Issue encountered when attempting to retrieve text input from text box within a C# (ASP.NET gridview) segment

Every time I attempt to retrieve a value from a textbox, I encounter this error (as shown in the image) and I am at a loss as to how to resolve it. My code is as follows: protected void Button3_Click(object sender, EventArgs e) { _controller = ...

The parameter 'Barable' cannot be assigned to the parameter 'T' as they are not compatible

Could anyone help me understand why this code isn't functioning as intended: class Fooable { foo: string; } class Barable extends Fooable { bar: boolean; } function simplifiedExample<T extends Fooable>(): Array<T> { let list ...

Exploring into the subdirectory

I am trying to redirect to a subfolder ASPX page from the index.html page upon page load, but I am encountering an error with the following code: window.location.href = 'URL= HMIS/Login.aspx'</script> Error Resource cannot be found. D ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

Designing a Tombstone with TypeScript

In TypeScript, I have certain values that are only necessary within the type system and not at runtime. I am seeking a way to void these values without losing their type information. The function bury illustrated below is intended to replace the actual v ...

Creating an Excel spreadsheet from an HTML table with compatibility across different web browsers

Does anyone know of a JavaScript function that can save an HTML table as an Excel file, meeting the criteria of being A. Developed in pure JavaScript and B. Compatible with browsers as far back as IE8? I've dedicated 2 full days to finding a solution ...

Using jQuery ajax with asynchronous set to 'true' causes my web application to freeze until the data is retrieved

I am currently working with a PHP-based web application that I did not create. Here is the AJAX request I am running: $.ajax({ type: 'POST', url: "/potato/ajax.php?module=test_module", dataType: 'json', async: true, ...

Cross-site communication with Ajax using both POST and GET requests

As a beginner in JavaScript, I'm facing challenges with implementing ajax POST and GET requests. While I can successfully do it using Google Postman as shown here https://i.sstatic.net/Cegxj.pnghttps://i.sstatic.net/ovJT0.png, the problem arises when ...

The Jquery click menu is functional, but appears completely translucent in Safari and the majority of mobile browsers

I have implemented a link that, when clicked, should reveal a menu on the website. This feature is specifically optimized for smaller browser windows with a breakpoint set at 965px. However, I am encountering some varied behaviors across different browsers ...

Attaching an event listener to elements with a specified Class name

Currently facing a challenge where I am trying to implement a function that captures click events on squares. The objective is to capture the click event on every button with the square class. import { Component, OnInit } from '@angular/core&apos ...

Encountering an error of "Cannot set headers after they are sent" when attempting to manage a user session during a test using the Chai request agent

We're currently facing a challenge with an error message stating Uncaught Error: Can't set headers after they are sent. when attempting to link a user sign-in to a test using chai-http. The test signs in a user already existing in the database v ...

Upon the initial loading of the React component, I am retrieving undefined values that are being passed from the reducer

Upon the initial loading of the React component, I am encountering an issue where the values originating from the reducer are showing up as undefined. Below is a snippet of my code: const [componentState, dispatchComponentState] = useReducer( versionReduc ...

What is the best way to collapse additional submenus and perform a search within a menu?

Whenever a sub-menu is activated, only the current sub-menu should be open while the others remain closed. I need the search function to be enabled on the text box and display all items containing the specified value while also changing the color of <a ...

What is the purpose of deserializing the user for every request using PassportJS?

While I have scoured the official documentation and various online resources, I am still unable to find a solution to what seems like an obvious question. When working with Passport.js, it is necessary to define two methods - one for serializing and one f ...

What is the reason for the global impact of CSS-Modules on html elements?

There is a file named mycomponent.module.css button { width: 10vw; min-width: 150px; } It seems like this CSS is being applied globally instead of just to the specific component where I imported it. Could it be that CSS modules only work on class ...

What are some ways to keep the text within the boundaries of the input box?

How can I prevent the letters from extending beyond the bar when typing a lot of characters? Your assistance in resolving this issue is greatly appreciated. <div id="tasks-container"> <div id="tasks-header"> ...