如何让list()方法等待数据加载到构造函数中,然后再将其promise 解析回调用方?

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());
})();

推荐答案

我建议让构造器将promise 从数据加载保存到this,然后list可以等待该promise :

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';
    
    this.initPromise = (async () => {
      const response = await fetch(this.url);
      this.employees = await response.json();
      this.dataLoaded = true;
      console.log(`work done: got ${this.employees.length} employees`);
    })();
  }

  async list() {
    await this.initPromise;
    return this.employees.map(m => `${m.firstName} ${m.lastName} (${m.id})`));
  }
}

如果加载尚未完成,则await将导致list等待多长时间.如果加载已完成,则initPromise处于已解析状态,list将或多或少立即恢复(当微任务队列执行时).

Javascript相关问答推荐

当我使用jQuery时,我的图标显示为[对象对象]

Express.js:以块形式发送响应

如何在react-Router-dom 6中Forking 路由?

想要检测字符串中的所有单词

如何使用CSS和JavaScript创建粘性、凝聚力的形状到形状(容器)变形?

积分计算和 colored颜色 判断错误

如何修复循环HTML元素附加函数中的问题?

字节数组通过echo框架传输到JS blob

如何从一个列表中创建一个2列的表?

仅针对RTK查询中的未经授权的错误取消maxRetries

在服务器上放置了Create Reaction App Build之后的空白页面

将本机导航路由react 到导航栏中未列出的屏幕?

将旋转的矩形zoom 到覆盖它所需的最小尺寸&S容器

虚拟滚动实现使向下滚动可滚动到末尾

如何在输入元素中附加一个属性为checkbox?

制作钢琴模拟器,并且在控制台中不会执行或显示该脚本

Html文件和客户端存储的相关问题,有没有可能?

在WordPress中使用带有WPCode的Java代码片段时出现意外令牌错误

为什么123[';toString';].long返回1?

如何在Press上重新启动EXPO-AV视频?