[英]Svelte / Vanilla JS - do I need to use .then() on awaiting an async function?
This is probably best explained with code:这可能最好用代码解释:
in my utils file I have created the following async function:在我的 utils 文件中,我创建了以下异步 function:
export async function post(fetch, url, body) {
const res = await fetch(url, {
method: 'POST',
body,
headers
});
return await res.json();
}
I've stripped down the function to avoid posting too much code.我已经剥离了 function 以避免发布太多代码。
Now in my.svelte component file, the function above is called as followed:现在在 my.svelte 组件文件中,上面的 function 调用如下:
async function handleLogin() {
const result = await post(fetch, 'https://accountingserver.dev/auth/login', {
email: email,
password: password
});
console.log(result);
}
In the above example, the result is output correctly as expected.在上面的示例中,结果是 output 与预期一样正确。 But I have found I can also do the following and get the same outcome:
但我发现我也可以执行以下操作并获得相同的结果:
async function handleLogin() {
post(fetch, 'https://accountingserver.dev/auth/login', {
email: email,
password: password
}).then((result) => {
console.log(result);
});
}
So my question, is any of the two methods more valid and if so.. why?所以我的问题是,这两种方法中的任何一种更有效吗?如果是的话……为什么?
It's a preference thing, but where possible you should lean towards using async/await
.这是一个偏好,但在可能的情况下,您应该倾向于使用
async/await
。 It makes your code cleaner and easier to read and also helps you avoid Promise Hell .它使您的代码更清晰,更易于阅读,还可以帮助您避免Promise Hell 。
You should note that some environments might not support async/await
as it is a newer feature, but most modern environments will likely natively support it.您应该注意,某些环境可能不支持
async/await
,因为它是一个较新的功能,但大多数现代环境可能会原生支持它。 In cases where async/await
is not supported, async function name(){}
syntax will not be allowed and you will need to use .then()
instead of await
.在不支持
async/await
的情况下,将不允许使用async function name(){}
语法,您需要使用.then()
而不是await
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.