首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何正确地将json数据分配到javascript类中?

如何正确地将json数据分配到javascript类中?
EN

Stack Overflow用户
提问于 2018-08-23 08:49:41
回答 1查看 23关注 0票数 0

我很难让for循环中的函数同步运行。

EmployeePrint.js内幕

代码语言:javascript
复制
fillData(item, taxObj) {
        let fullName = item.getFullName();
        let timePeriod = item.getTimePeriod();
        let grossIncome = item.getGrossIncome();
        let incomeTax = item.getIncomeTax(taxObj);
        let netIncome = item.getNetIncome();
        let mySuper = item.getSuper();

        this.name = fullName;
        this.payPeriod = timePeriod;
        this.grossIncome = grossIncome;
        this.incomeTax = incomeTax;
        this.netIncome = netIncome;
        this.mySuper = mySuper;

        return this;
    }

项目为employee对象。它有一些方法,我在fillData中运行它

代码语言:javascript
复制
async print(arr, fileName, taxObj) {
        let buf = [];

        arr.map(async (item) => {
            let ep = new EmployeePrint();
            ep = ep.fillData(item, taxObj);
            buf.push(ep);
        });

        return await this.printPromise(buf, fileName);
    }

在填充数据之后,我将employee对象推入数组以便稍后打印。

我的问题是,我不知道如何确保在每次迭代中完成所有函数。

完整的项目在这里:https://github.com/kenpeter/mb_new/tree/extend_base

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-23 08:55:51

对于初学者,您应该调用forEach并推送到buf中,或者只使用从map返回的值,而不是创建buf。

其次,如果您想在循环中等待(而不是映射或forEach),或者只是映射到promises并等待所有内容,则应该使用for循环。

代码语言:javascript
复制
async print(arr, fileName, taxObj) {
  let buf = [];

  const promises = arr.map((item) => {
    let ep = new EmployeePrint();
    ep = ep.fillData(item, taxObj);
    buf.push(ep);
    return this.printPromise(buf, fileName);
  });
  await Promise.all(promises)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51976945

复制
相关文章

相似问题

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