Shr*_*rma 11 javascript callback promise reactjs jestjs
我在反应中有以下代码。
useEffect(() => {
(async () => {
await httpClient
.get(`${config.resourceServerUrl}/inventory/`)
.then((response) => {
setSponsor(response.data.sponsor);
setAddress(response.data.address);
setPhaseOfTrial(response.data.phaseOfTrial);
})
.catch((error) => {
alert(error);
});
})();
}, []);
Run Code Online (Sandbox Code Playgroud)
这段代码运行成功。唯一的问题是,它在玩笑测试用例中失败了。
describe('ListInventory', () => {
it('should render successfully', () => {
const { baseElement } = render(<ListInventory />);
expect(baseElement).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
下面是错误。
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read properties of undefined (reading 'get')".] {
code: 'ERR_UNHANDLED_REJECTION'
}
Run Code Online (Sandbox Code Playgroud)
我已经在使用catch块了。代码有什么问题?你能帮我做同样的事吗?
NeE*_* TK 10
尝试使用 try-catch 块处理 Promise,如下所示:
useEffect(() => {
(async () => {
try {
let response = await httpClient.get(
`${config.resourceServerUrl}/inventory/`
);
setSponsor(response.data.sponsor);
setAddress(response.data.address);
setPhaseOfTrial(response.data.phaseOfTrial);
} catch(error) {
alert(error);
}
})();
}, []);
Run Code Online (Sandbox Code Playgroud)
或者
useEffect(() => {
(async () => {
let response = await httpClient.get(
`${config.resourceServerUrl}/inventory/`
);
setSponsor(response.data.sponsor);
setAddress(response.data.address);
setPhaseOfTrial(response.data.phaseOfTrial);
})().catch(e=>alert(e));
}, []);
Run Code Online (Sandbox Code Playgroud)
小智 1
执行此操作的最佳方法如下:
useEffect(() => {
(async () => {
let response = async () => await httpClient.get(
`${config.resourceServerUrl}/inventory/`
);
response
.then((res) => {
setSponsor(res.data.sponsor);
setAddress(res.data.address);
setPhaseOfTrial(res.data.phaseOfTrial);
}).catch((error) => {
alert(error);
})
})();
}, []);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74312 次 |
| 最近记录: |