How do I get the list()
method to wait for the data to be loaded in the constructor before it resolves its promise back to the caller?
import fetch from 'node-fetch';
class Employees {
constructor() {
if (Employees._instance) {
return Employees._instance
}
Employees._instance = this;
this.employees = [];
this.dataLoaded = false;
this.url = 'https://raw.githubusercontent.com/graphql-compose/graphql-compose-examples/master/examples/northwind/data/json/employees.json';
(async () => {
const response = await fetch(this.url);
this.employees = await response.json();
this.dataLoaded = true;
console.log(`work done: got ${this.employees.length} employees`);
})();
}
list() {
return new Promise((resolve) => {
resolve(this.employees.map(m => `${m.firstName} ${m.lastName} (${m.id})`));
});
}
}
const employees = new Employees();
(async () => {
console.log(await employees.list());
})();