【问题标题】:try-catch & async await change order in js?js中的try-catch和异步等待更改顺序?
【发布时间】:2019-07-29 17:20:10
【问题描述】:

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

我测试我的代码。 但结果和我的不一样。

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

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
});

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

【问题讨论】:

  • 什么是assert.detailEqual
  • 那是因为 console.log 不等待回调完成

标签: javascript async-await try-catch


【解决方案1】:

我相信您拥有的async 功能没有用。 要让它工作,await 应该接收Promise 作为返回值。

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

最好不使用任何async-await,无论哪个函数完成都会先打印结果。

【讨论】:

  • 是的。但我有Promise 其他代码。所以,我需要async await。 TT
猜你喜欢
  • 2017-02-06
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 2019-02-11
  • 2016-01-26
  • 2018-12-20
相关资源
最近更新 更多