首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得JavaScript类方法以等待返回数据,直到加载了构造函数中的数据?

如何获得JavaScript类方法以等待返回数据,直到加载了构造函数中的数据?
EN

Stack Overflow用户
提问于 2022-03-10 05:02:56
回答 2查看 244关注 0票数 2

如何让list()方法等待将数据加载到构造函数中,然后它才能将其承诺返回给调用方?

代码语言:javascript
复制
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());
})();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-03-10 05:12:54

我建议构造函数将数据加载到this中的承诺保存到list上,然后list可以等待这个承诺:

代码语言:javascript
复制
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将或多或少地立即恢复(当微任务队列执行时)。

票数 5
EN

Stack Overflow用户

发布于 2022-03-10 05:35:09

使用Deferred对象。

延迟表示尚未完成的工作

代码语言:javascript
复制
// fetch mock with 3 seconds wait
fetch = () => {
     return new Promise((resolve) => {
         setTimeout(() => {
             resolve({
                 json: () => new Promise((r) => r([
                        {firstName: 'Arthur', lastName: 'Pym', id: 1},
                        {firstName: 'August', lastName: 'Barnard', id: 2},
                        {firstName: 'M.', lastName: 'Poe', id: 3}
                 ]))
             });
         }, 3000);
     });
}

class MyDeferred {
    resolve = null;
    reject = null;
    promise = null;
    constructor() {
        this.promise = new Promise((res, rej) => {
            this.resolve = res;
            this.reject = rej;
        });
    }
}

class Employees {
    deferred = new MyDeferred();
    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;
            this.deferred.resolve();
            console.log(`work done: got ${this.employees.length} employees`);
        })();
    }

    list() {
        return new Promise((resolve) => {
            this.deferred.promise.then(() => {
                resolve(this.employees.map(m => `${m.firstName} ${m.lastName} (${m.id})`));
            });
        });
    }

}

const employees = new Employees();

(async () => {
    console.log(await employees.list());
})();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71419074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档