try-catch和async等待js中的更改顺序?

时间:2019-07-29 09:03:36

标签: javascript async-await try-catch

我有一个问题。 我做函数test()和assert();

我测试我的代码。 但是结果却与我不同。

当我在test()函数中使用async等待时。 结果是

should support flattening of nested arrays : fail
should support filtering of arrays : fail
support notEqual : ok
adds 1 + 2 to equal 3 : ok

但是我在函数test()中删除了异步等待。 结果是

support notEqual : ok
adds 1 + 2 to equal 3 : ok
should support flattening of nested arrays : fail
should support filtering of arrays : fail

为什么?

const _ = require("lodash");

const sum = (a, b) => {
  return a + b;
};

const isEven = n => {
  return n % 2 == 0;
};

const appendLazy = (arr, data, time) => {
  return new Promise(resolve => {
    setTimeout(() => {
      arr.push(data);
      resolve(arr);
    }, time);
  });
};

async function test(msg, callback) {
  try {
    await callback();
    console.log(`${msg} : ok`);
  } catch (e) {
    console.log(`${msg} : fail`);
  }
}

const assert = {
  equal: (targetA, targetB) => {
    if (targetA !== targetB) throw Error;
  },
  notEqual: (targetA, targetB) => {
    if (targetA === targetB) throw Error;
  }
};

test("support notEqual", () => {
  assert.notEqual(undefined, null); //pass
});

test("adds 1 + 2 to equal 3", () => {
  assert.equal(1 + 2, 3); //pass
});

test("should support flattening of nested arrays", function() {
  assert.detailEqual([1, 2, 3, 4], [1, 2, 3, 5]); //fail
});

test("should support filtering of arrays", function() {
  const arr = [1, 2, 3, 4, 5, 6];
  assert.detailEqual(_.filter(arr, isEven), [2, 4, 5, 6]); //fail
});

我必须在测试功能中使用异步等待。 为什么原因不同?

1 个答案:

答案 0 :(得分:1)

我相信您拥有的async函数没有用。 为了使其正常工作,await应该收到Promise作为返回值。

根据您发布的功能,没有一个函数返回任何承诺(appendLazy除外,但从未使用过)。

这与不使用任何async-await一样好,无论哪个函数完成将首先打印结果。

相关问题