I am trying to make this code return each employees name.
var company = {
employees: [
{
name: "doug"
},
{
name: "AJ"
}
],
getName: function(employee){
return employee.name
},
getNames: function(){
return this.employees.map(this.getName)
},
delayedGetNames: function(){
setTimeout(this.getNames,500)
}
}
console.log(company.delayedGetNames());
However, when I run the code I get "TypeError: Cannot read property 'map' of undefined"
I have tried doing
setTimeout(this.getNames.bind(this),500)
I just get undefined returned to me.
Can anyone help me out?
You need to add a callback to your function in order to get the names.
var company = {
employees: [
{
name: "doug"
},
{
name: "AJ"
}
],
getName: function(employee){
return employee.name
},
getNames: function(){
return this.employees.map(this.getName)
},
delayedGetNames: function(cb){
setTimeout(()=>cb(this.getNames()),500)
}
}
company.delayedGetNames(names => console.log(names))
Or, using Promise, you could write something like this:
var company = {
employees: [
{
name: "doug"
},
{
name: "AJ"
}
],
getName: function(employee){
return employee.name
},
getNames: function(){
return this.employees.map(this.getName)
},
delayedGetNames: function() {
return new Promise(resolve => setTimeout(() => resolve(this.getNames()), 1000));
}
}
company.delayedGetNames().then(console.log);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With