0

I have a few asynchronous calls I want to execute before my final call, and i have similar method to this stackoverflow answer.

Here is the code in 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");
})

What the above code produced:

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

while what I am expecting:

"start"
"janes"
"james"
"jo"
"john"
"josh"
[undefined, undefined, undefined, undefined, undefined]
"finsh"
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
roger
  • 1,225
  • 2
  • 17
  • 33

1 Answers1

4

You're not returning the promises created in printName to the request array, so Promise.all is being called on an array of undefineds (and, as a result, resolves immediately). Chain and return the promises instead.

Often, when you use Promise.all, you want the resolved array to contain values and not undefineds - for that, also return name inside getSomething.then so that the Promise.all will resolve 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; // add this line too
  });
}

Working snippet in ordinary 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("finsh");
})
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320