如果您等待其响应,为什么还要使用异步功能呢?

发布于 2025-02-13 18:22:08 字数 60 浏览 1 评论 0原文

为什么我们使用异步函数,如果我们将等待它们的响应进行等待,在这种情况下,Syncronus函数有什么区别?

Why we using async function if then we use await for waiting their response, in this case what's the difference between a syncronus function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雄赳赳气昂昂 2025-02-20 18:22:08

以下是使用异步/等待的比较,然后:

function fetchData() {
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => response.json());
}

async function asyncMain() {
    console.log('Start');

    console.log(await fetchData());

    console.log('End');
}

function main() {
    console.log('Start');

    fetchData().then(data => { console.log(data) });

    console.log('End');
}

main();
// Output
// Start
// End
// { "userId": 1, id": 1, "title": "delectus aut autem", "completed": false}

asyncMain();
// Output
// Start
// { "userId": 1, id": 1, "title": "delectus aut autem", "completed": false}
// End

异步函数允许您使用等待 +使函数返回承诺( https://developer.mozilla.org/fr/docs/web/javascript/reference/reference/global_objects/promise

如您所见'。同时函数打印“ end”,然后一旦解决了对API的请求,则打印结果。

为了简化,等待“等待答案,然后执行代码的其余部分”,然后表示“收到响应时...”然后执行,然后执行代码结束

Here is a comparison between using async / await and then :

function fetchData() {
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => response.json());
}

async function asyncMain() {
    console.log('Start');

    console.log(await fetchData());

    console.log('End');
}

function main() {
    console.log('Start');

    fetchData().then(data => { console.log(data) });

    console.log('End');
}

main();
// Output
// Start
// End
// { "userId": 1, id": 1, "title": "delectus aut autem", "completed": false}

asyncMain();
// Output
// Start
// { "userId": 1, id": 1, "title": "delectus aut autem", "completed": false}
// End

async function allow you to use await + make the function return a promise (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise)

As you can see, await block the function execution and wait for the result before printing 'End'. While syncronious function print 'End' then print the result once the request to the api is resolved.

To simplify, await means "wait for the answer then execute the rest of the code" while then means "when you receive the response do ..." then it execute then end of the code

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文