异步/等待
来源:dev.to
时间:2024-11-02 15:48:58 170浏览 收藏
哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《异步/等待》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
异步/等待
与 promise 相比,async/await 是一种更新的异步代码编写方式。 async/await 的主要优点是提高了可读性并避免了承诺链。 promise 可能会变得很长、难以阅读,并且可能包含难以调试的深层嵌套回调。
例子
回想一下我们之前的获取。
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('error:', error)) .finally(() => console.log('all done'));
使用 async/await,代码可以重构为如下所示:
async function fetchdata() { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); console.log(data); } catch (error) { console.error('error:', error); } finally { console.log('all done'); } } fetchdata();
虽然可能多了几行代码,但这个版本更容易阅读,因为它类似于普通的同步函数。此外,如果 .then() 语句内的函数更复杂,则可读性和可调试性将受到更大的影响。 async/await 示例更加清晰。
示例 2:从餐厅订餐
async/await 的结构
async/await 函数有两个基本部分:async 和await。 async 关键字加在函数声明前,await 用于异步任务开始时。
让我们以从餐厅点餐的例子来说明这一点:
// simulate the order process with async/await async function foodorder() { console.log("ordering food..."); await new promise(resolve => settimeout(resolve, 2000)); // wait 2 seconds for food to be prepared return "your food is ready!"; } // simulate the eating process function eatfood(order) { console.log(order); // this logs "your food is ready!" console.log("enjoying the meal!"); } // simulate continuing the conversation function continueconversation() { console.log("while waiting, you continue chatting with friends..."); } async function orderfood() { console.log("you've arrived at the restaurant."); const order = await foodorder(); // place the order and wait for it to be ready continueconversation(); // chat while waiting eatfood(order); // eat the food once it arrives } orderfood();
输出将是
You've arrived at the restaurant. Ordering food... While waiting, you continue chatting with friends... Your food is ready! Enjoying the meal!
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。
声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
230 收藏
-
346 收藏
-
217 收藏
-
307 收藏
-
269 收藏
-
141 收藏
-
343 收藏
-
492 收藏
-
343 收藏
-
216 收藏
-
351 收藏
-
483 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习