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"