异步功能不等待等待

时间:2018-10-19 17:48:20

标签: javascript node.js async-await jestjs

我有许多异步功能,我从文件中导入json,然后设置字段。我正在等待导入json。先前,它通过等待json然后处理数据来顺序执行。我以前曾经使用过Mocha,最近才开始迁移到Jest,那时我的所有测试和功能都开始崩溃。

我不确定我是否正确理解异步功能。但是它以前曾经工作得很好,现在已经不行了。下面是示例:

async build_transaction_request({reference=util.id_generator(), type="XYZ", amount=25, currency="USD", timestamp=util.timestamp_millis()}={}){
    let transactions = await config_util.get_payload("transactions")
    let x_transaction = transactions.xTransaction
    x_transaction.reference = reference
    x_transaction.type = type
    x_transaction.amount = amount
    x_transaction.currency = currency
    x_transaction.timestamp = timestamp
    return x_transaction
}

我收到此错误:

  

TypeError:无法设置未定义的属性“引用”

下面是其他两个功能:

async load_data(file_path) {
  await delete require.cache[require.resolve(file_path)]
  let data = await require(file_path);
  return data
}

async get_payload(file_name) {
  let payload = await this.load_data(this.root_dir + '/resources/payload/' + file_name + ".json")
  return payload
}

下面是我的测试中调用build_transaction_request函数的代码:

test('Test xyz returns 201', async() => {
      //......some code.....

      var[instruction, x_transaction, token] = await Promise.all([

          helper.build_instruction_request({
            type: "CURRENCY",
            value: value,
            rate: rate
          }),
          helper.build_transaction_request({
            amount: amount
          }),
          helper.build_token_request(token_id)
      ]);
});

2 个答案:

答案 0 :(得分:0)

所以我想出了问题。我更改了导入json的方式。现在我正在使用readFileSync(file_path);现在问题解决了。所以我认为这是由于同时通过多个功能访问同一文件。非常感谢大家。

答案 1 :(得分:-1)

问题是btnSearch_Click返回一个对象,该对象一旦解析,要么缺少await config_util.get_payload("transactions")属性,要么由xTransaction手动设置。一旦尝试使用undefined的属性,该代码将被炸毁,这是您正在使用的undefined。就像说:x_transaction.reference = reference ....这样,代码就开始繁荣起来。您无法为内存中不存在的内容分配值。

您的undefined.reference = reference只是根据您提供给get_payload的某些文件路径来解决承诺并返回结果。

您是否查看了要传递给load_data的参数?

load_data

您那里有一个空格,所以可能不正确。无论您要喂到那里,都找不到json ...

相关问题