-1

Can someone help me define an object property asynchronously? My example below returns `name : undefined and I can't find any strategies on how to do this synchronously...

function returnName () {
    setTimeout(function() { 
    return 'John Wick'
  }, 3000);
}

const person = {
    name: returnName(),
  age: 23
}

console.log(person) // person.name returns `undefined`

Thanks in advance!

John Grayson
  • 1,378
  • 3
  • 17
  • 30

1 Answers1

0

Are you able to use something like a Promise to set/log the name of the person only once the name has resolved from function returnName() whether that's through a setTimeout() or an async DB call? A Promise would give you a simple, effective way to only execute an action once the async method has completed and provides you options for handling successes and errors via .then() and .catch().

function returnName() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
        return resolve('John Wick');
    }, 3000);
  });
}

let person = { age: 23 };

returnName().then(function(name) {
  person.name = name;
  console.log(person);
});

Here is a jsfiddle demonstrating the functionality.

Hopefully this helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91