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"