[英]Why do I need to use async await to call a async function in React while it doesn't need in pure JS file
[英]Svelte / Vanilla JS - do I need to use .then() on awaiting an async function?
这可能最好用代码解释:
在我的 utils 文件中,我创建了以下异步 function:
export async function post(fetch, url, body) {
const res = await fetch(url, {
method: 'POST',
body,
headers
});
return await res.json();
}
我已经剥离了 function 以避免发布太多代码。
现在在 my.svelte 组件文件中,上面的 function 调用如下:
async function handleLogin() {
const result = await post(fetch, 'https://accountingserver.dev/auth/login', {
email: email,
password: password
});
console.log(result);
}
在上面的示例中,结果是 output 与预期一样正确。 但我发现我也可以执行以下操作并获得相同的结果:
async function handleLogin() {
post(fetch, 'https://accountingserver.dev/auth/login', {
email: email,
password: password
}).then((result) => {
console.log(result);
});
}
所以我的问题是,这两种方法中的任何一种更有效吗?如果是的话……为什么?
这是一个偏好,但在可能的情况下,您应该倾向于使用async/await
。 它使您的代码更清晰,更易于阅读,还可以帮助您避免Promise Hell 。
您应该注意,某些环境可能不支持async/await
,因为它是一个较新的功能,但大多数现代环境可能会原生支持它。 在不支持async/await
的情况下,将不允许使用async function name(){}
语法,您需要使用.then()
而不是await
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.