Svelte / Vanilla JS - 我需要在等待异步函数时使用 .then() 吗?

Svelte / Vanilla JS - do I need to use .then() on awaiting an async function?

这可能最好用代码解释:

在我的 utils 文件中,我创建了以下异步函数:

export async function post(fetch, url, body) {
    const res = await fetch(url, {
        method: 'POST',
        body,
        headers
    });
    return await res.json();
}

我已经精简了函数以避免发布太多代码。

现在在我的 .svelte 组件文件中,上面的函数调用如下:

async function handleLogin() {
    const result = await post(fetch, 'https://accountingserver.dev/auth/login', {
        email: email,
        password: password
    });
    console.log(result);
}

在上面的例子中,结果按照预期正确输出。但我发现我也可以执行以下操作并获得相同的结果:

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.