I am trying to make a new class like this:
const request = require("request");
class Person {
constructor(personName) {
request(`http://personapi.com/name/${personName}`, (err, res, body) => {
body = JSON.parse(body);
this.name = body.name;
this.age = body.age;
this.gender = body.gender;
}
}
}
let person = new Person("Donald Trump");
console.log(person.name);
Doing the above does not work, because it creates the new person which has no attributes yet, because the request is not done loading yet. If I do something like:
let person = new Person("Donald Trump");
setTimeout(() => {
console.log(person.name);
}, 1000);
It works fine. I know this is because it's asynchronous. How do I make sure let person
is not actually set, before the request is done? Don't worry about code blocking.