同步等待 异步等待_异步/等待和承诺的解释
同步等待 异步等待
The async
/ await
operators make it easier to implement many async Promises. They also allow engineers to write clearer, more succinct, testable code.
async
/ await
运算符使实现许多异步Promises变得更加容易。 它们还允许工程师编写更清晰,更简洁,可测试的代码。
To understand this subject, you should have a solid understanding of how Promises work.
要理解此主题,您应该对Promises的工作方式有扎实的了解。
基本语法 (Basic Syntax)
function slowlyResolvedPromiseFunc(string) { return new Promise(resolve => {setTimeout(() => {resolve(string);}, 5000);});
}async function doIt() {const myPromise = await slowlyResolvedPromiseFunc("foo");console.log(myPromise); // "foo"
}doIt();
There are a few things to note:
有几件事要注意:
The function that encompasses the
await
declaration must include theasync
operator. This will tell the JS interpreter that it must wait until the Promise is resolved or rejected.包含
await
声明的函数必须包含async
运算符。 这将告诉JS解释器,它必须等待直到Promise被解决或拒绝为止。The
await
operator must be inline, during the const declaration.在const声明期间,
await
操作符必须是内联的。This works for
reject
as well asresolve
.这既适用于
reject
,也适用于resolve
。
嵌套的承诺与Async
/ Await
(Nested Promises vs. Async
/ Await
)
Implementing a single Promise is pretty straightforward. In contrast, Chained Promises or the creation of a dependency pattern may produce “spaghetti code”.
实现一个Promise非常简单。 相反,链式承诺或依赖模式的创建可能会产生“意大利面条代码”。
The following examples assume that the request-promise
library is available as rp
.
以下示例假定request-promise
库可以作为rp
。
链接/嵌套的承诺 (Chained/Nested Promises)
// First Promise
const fooPromise = rp("http://domain.com/foo");fooPromise.then(resultFoo => {// Must wait for "foo" to resolveconsole.log(resultFoo);const barPromise = rp("http://domain.com/bar");const bazPromise = rp("http://domain.com/baz");return Promise.all([barPromise, bazPromise]);
}).then(resultArr => {// Handle "bar" and "baz" resolutions hereconsole.log(resultArr[0]);console.log(resultArr[1]);
});
async
await
承诺 (async
and await
Promises)
// Wrap everything in an async function
async function doItAll() {// Grab data from "foo" endpoint, but wait for resolutionconsole.log(await rp("http://domain.com/foo"));// Concurrently kick off the next two async calls,// don't wait for "bar" to kick off "baz"const barPromise = rp("http://domain.com/bar");const bazPromise = rp("http://domain.com/baz");// After both are concurrently kicked off, wait for bothconst barResponse = await barPromise;const bazResponse = await bazPromise;console.log(barResponse);console.log(bazResponse);
}// Finally, invoke the async function
doItAll().then(() => console.log('Done!'));
The advantages of using async
and await
should be clear. This code is more readable, modular, and testable.
使用async
和await
的优势应该很明显。 此代码更具可读性,模块化和可测试性。
It’s fair to note that even though there is an added sense of concurrency, the underlying computational process is the same as the previous example.
可以公平地注意到,即使增加了并发感,底层的计算过程也与前面的示例相同。
处理错误/拒绝 (Handling Errors / Rejection)
A basic try-catch block handles a rejected Promise.
基本的try-catch块可处理被拒绝的Promise。
async function errorExample() {try {const rejectedPromise = await Promise.reject("Oh-oh!");} catch (error) {console.log(error); // "Uh-oh!"}
}errorExample();
翻译自: https://www.freecodecamp.org/news/async-await-and-promises/
同步等待 异步等待
相关文章:

使用 GDB 调试多进程程序
使用 GDB 调试多进程程序 来源 https://www.ibm.com/developerworks/cn/linux/l-cn-gdbmp/index.html GDB 是 linux 系统上常用的 c/c 调试工具,功能十分强大。对于较为复杂的系统,比如多进程系统,如何使用 GDB 调试呢?考虑下面这…

理解Lucene索引与搜索过程中的核心类
理解索引过程中的核心类 执行简单索引的时候需要用的类有: IndexWriter、Directory、Analyzer、Document、Field 1、IndexWriter IndexWriter(写索引)是索引过程的核心组件,这个类负责创建新的索引,或者打开已有的索引…

lua的table+setfenv+setmetatable陷阱
--file1.lua x funciton() print("this is x") end ------------- --file2.lua local t {} local _G _G setfenv(1,t) --设置了这个之后,只要是在本文件中对未声明变量的访问,全部会导致递归。 _G.setmetatable(t, { __index fu…

rest api_REST API
rest api历史 (History) REST stands for Representational State Transfer protocol. Roy Fielding defined REST in his PhD dissertation in 2000.REST代表再表象小号泰特贸易交接协议。 Roy Fielding在2000年的博士学位论文中定义了REST。 什么是REST API? (Wh…

0414复利计算6.0--结对
结对同伴:姓名:柯晓君学号:201406114210博客园地址:http://www.cnblogs.com/950525kxj/一、项目简介 开发工具:eclipse 开发语言:java 主要功能:复利单利的计算、贷款的计算以及投资运算三大功能…

把简单做到极致
我真的还没有认真想过我已经是一名即将毕业的大三学生了。关于自己的过去,关于自己的未来。 有时候也有想过好好反思一下自己的过去,却发现自己的过去总是被太多的无奈与遗憾填满。有时候想畅想一下自己的未来,却发现未来总是充满了未知与迷茫…

作为程序员,要取得非凡成就需要记住的15件事。
作为程序员,要取得非凡成就需要记住的15件事。1、走一条不一样的路在有利于自己的市场中竞争,如果你满足于“泯然众人矣”,那恐怕就得跟那些低工资国家的程序员们同场竞技了。2、了解自己的公司以我在医院、咨询公司、物流企业以及大技术公司…

craigslist_Craigslist,Wikipedia和丰富经济
craigslistYou’ve heard it before. Maybe you’ve even said it. “There’s no such thing as a free lunch.”你以前听过 也许你甚至已经说过了。 “没有免费的午餐之类的东西。” “You can’t get something for nothing.”“你不能一无所获。” “Somebody has to pay…

EXCEL基础篇(二)
本章主要内容 一、单元格操作 二、插入批注 三、自动求和 四、填充序列 五、查找、替换 六、对齐方式 七、定位 八、插入形状及设置形状 九、页面设置 一单元格操作 1、插入 a、插入单元格 一个单元格选中状态---右击插入(单元左右移)--即可 b、插入单…

lua5.2调用c函数成功的例子
1. main.c-----------------//动态库#include <stdio.h>#include <stdlib.h>#include <string.h>#ifdef _cplusplusextern "C"{#endif#include <lua.h>#include <lauxlib.h>#include <lualib.h>static void checktoptype(lua_St…

【转】Android Activity原理以及其子类描述,androidactivity
Android Activity原理以及其子类描述,androidactivity 简介 Activity是Android应用程序组件,实现一个用户交互窗口,我们可以实现布局填充屏幕,也可以实现悬浮窗口。一个app由很多个Actvitiy组合而成,它们之间用intent-…

python 文件追加写入_Python写入文件–解释了打开,读取,追加和其他文件处理功能
python 文件追加写入欢迎 (Welcome) Hi! If you want to learn how to work with files in Python, then this article is for you. Working with files is an important skill that every Python developer should learn, so lets get started.嗨! 如果您想学习如何…

带有中文的字符串各个字符的获取c++程序
简单易懂,上代码: #include <iostream> #include <cstring> #include <string> #include <cstdlib> #include <vector> using namespace std;class CStr{char *c;typedef struct {int start;bool isChinese;} counter;int…

C#时间格式化(Datetime)用法详解
Datetime.ToString(String, IFormatProvider) 参数format格式详细用法: 格式字符关联属性/说明dShortDatePatternDLongDatePatternf完整日期和时间(长日期和短时间)FFullDateTimePattern(长日期和长时间)g常规…

python添加数组元素_Python列表附录–如何向数组添加元素,并附带示例说明
python添加数组元素欢迎 (Welcome) Hi! If you want to learn how to use the append() method, then this article is for you. This is a powerful list method that you will definitely use in your Python projects.嗨! 如果您想学习如何使用append()方法&…

学习进度条--第七周
第七周 所花时间(包括上课时间) 10小时(包括上课2小时) 代码量(行) 152 博客量(篇) 2篇(包括团队博客) 了解到的知识点 对组内开发的软件进行讨论&am…

Mybatis获取插入记录的自增长ID
转自:http://blog.csdn.net/tolcf/article/details/39035259 1.在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名,而不是表格的字段名。 <insert id"insert" parameter…

android中一种不支持的lua操作
今天写了一段lua代码,在win32中正常运行,在android中运行无效。 大概是这样的: ------file1.lua----- local t {} t.str "this is file1.t" return t ---------------------- -----file2.lua------ local t require &quo…

23岁一无所有怎么办_我搬到国外去创业,然后一无所有。
23岁一无所有怎么办以我的名字还不到一美元,它仍然感觉不像是最低点。 (With not even a dollar to my name, it still didn’t feel like rock bottom.) When you tell someone you’re working for a startup, they’ll either think you’re gonna be really ric…

正则表达式的基本入门
一、正则表达式基本语法 1. 两个特殊的符号‘^’和‘$’。他们的作用分别指出一个字符串的开始和结束。 2. 其他还有‘*’,‘’,‘?’这三个符号,表示一个或一序列字符重复出现的次数 "ab{2}" ---表示一个字符串有一个…

多继承中虚基类构造函数的一种调用规则
规则:如果父类中有虚基类(A),且有一个直接基类(B)是虚基类的子类,那么子类(C或D)若不显式调用虚基类的有参数构造函数,它的直接基类(B)即使在构造列表中调用了非默认构造函数,那么也会直接调用虚基类的默认构造函数。 …

Android 常见异常及解决办法
前言 本文主要记录 Android 的常见异常及解决办法,以备以后遇到相同问题时可以快速解决。 1. java.lang.NullPointerException: Attempt to invoke virtual method void android.widget.TextView.setText(java.lang.CharSequence) on a null object reference 1) …
aws s3 静态网站_如何将静态网站或JAMstack应用托管并部署到AWS S3和CloudFront
aws s3 静态网站S3 and CloudFront are AWS cloud services that make serving static assets powerful and cheap. How can we host a simple static website or JAMstack app on it?S3和CloudFront是AWS云服务,使服务静态资产功能强大且价格便宜。 我们如何在其上…

图像预处理第7步:标准归一化
图像预处理第7步:标准归一化将分割出来的各个不同宽、高的数字字符宽、高统一 //图像预处理第7步:标准归一化 //将分割出来的各个不同宽、高的数字字符宽、高统一 void CChildView::OnImgprcStandarize() {StdDIBbyRect(m_hDIB,w_sample,h_sample);//在…

8. 进制转化的函数
一,表示进制的单词 bin:二进制 oct:八进制 dec:十进制 hex:十六进制二,四种进制的数据表示方式 $bin0b1010; //二进制数字写法(暂时不学 ) …

二叉树广度优先遍历
#include <iostream> using namespace std;struct Node{//二叉树节点int value;Node *left;Node *right; };struct queue{//辅助队列int head;int tail;int len;//队列长度,遍历时用Node ** list;//队列内容void push(Node *n){list[tail] n;len;}Node * pop…

phaser.min.js_如何使用Phaser 3,Express和Socket.IO构建多人纸牌游戏
phaser.min.jsIm a tabletop game developer, and am continually looking for ways to digitize game experiences. In this tutorial, were going to build a multiplayer card game using Phaser 3, Express, and Socket.IO.我是桌面游戏开发人员,并且一直在寻找…

VirtualBox - RTR3InitEx failed with rc=-1912 (rc=-1912)
有一天重启电脑后虚拟机virtual box突然打不开了,提示类似 https://askubuntu.com/questions/900794/virtualbox-rtr3initex-failed-with-rc-1912-rc-1912 参考帖子中查看了一下包的情况dpkg --list virtualbox-* | grep ii 结果:ii virtualbox-dkms …

边工作边刷题:70天一遍leetcode: day 27
Permutation Sequence 原理:一个permutation是n位,在第i位的值取决于有多少个i-1位的组合。这i-1位的组合是在高位pick完之后剩下的数中 细节: 不同于decimal,位数是固定的,所以不能用k>0作为循环条件(这…

基本数据结构(图: 基本结构,DFS,prim算法, kruskal算法)
#include <iostream> using namespace std; //约定: //1. 图是由很多节点(VERTEX)构成的, 因此图结构是由一个VERTEX的链表构成的, 每个VERTEX则需要有一个id,也就是start, 取start是为了跟LINE更直观地结合。 //2. 每个节点关联着很多(LINE)构成,因此每个VER…