使用类将所有数据存储在对象中

时间:2019-02-14 06:22:18

标签: javascript node.js ecmascript-6 async-await

我使用了一个类来获取所有要存储在一个对象中的数据。但是成功运行后,该对象是未定义的,似乎数据存储在object(Alloptions)中。

我已经尝试过,但是找不到合适的做法

router.get('/:category', (req, res) => {
  let AllOptions;
  let cat4;

  AllOptions = new GetAllOptions(); //show undefined
  let category = req.params.category.replace(/-/g, ' ')
  console.log(AllOptions)
  for (i = 0; i < AllOptions.categories.length; i++) {
    console.log(AllOptions.categories[i].categoryName.replace(/-/g, ' ').toLowerCase())
    console.log(category)
    if (AllOptions.categories[i].categoryName.replace(/-/g, ' ').toLowerCase() == category) {
      cat4 = AllOptions.categories[i].categoryId - 1
    }
  }
})

类对象

class GetAllOptions {
  constructor() {
    this.categories = {};
    this.languages = {};
    this.getJobCategories();
  }
  async getJobCategories() {
    await Category.getAllCategories((err, response) => {

      if (err) {
        //?? how error flash dont know
        return res.json({
          error: ERROR_MSG,
        });
      }
      if (response.length > 0) {
        for (let i = 0; i < response.length; i++) {
          this.categories[response[i].categoryId] =
            response[i];
        }

        for (let i = 0; i < response.length; i++) {
          this.categoriesNames[response[i].categoryName] =
            response[i];
        }

      }
    })
    this.getJobLanguages();
  }

  async getJobLanguages() {
    await Category.getAllLanguages((err, response) => {
      if (err) {
        //?? how error flash dont know
        return res.json({
          error: ERROR_MSG,
        });
      }
      if (response) {
        for (let i = 0; i < response.length; i++) {
          this.languages[response[i].languageId] =
            response[i];
          console.log(this.languages[response[i].languageId])
        }

        for (let i = 0; i < response.length; i++) {
          this.languagesNames[response[i].languageName] =
            response[i];
        }
      }
    })
  }
}

我想等到类运行完成并获取所有数据,但此处显示未定义

1 个答案:

答案 0 :(得分:0)

您可以异步构造GetAllOptions对象:

      constructor (async_param) {
            if (typeof async_param === 'undefined') {
                throw new Error('Cannot be called directly');
            }
        }
        static async build () {
            var async_result = await getJobCategories()();
            return new myClass(async_result);
        }