gpt4 book ai didi

javascript - try-catch 和 async wait js 中的更改顺序?

转载 作者:行者123 更新时间:2023-12-02 23:13:38 25 4
gpt4 key购买 nike

我有一个问题。我制作函数 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() 中的 async wait。结果是

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

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

最佳答案

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

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

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

关于javascript - try-catch 和 async wait js 中的更改顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57250456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com