当前位置:网站首页>Realize all, race, allsettled and any of the simple version of promise by yourself
Realize all, race, allsettled and any of the simple version of promise by yourself
2022-07-07 12:29:00 【Xiaoding Chong duck!】
Supplementary knowledge :
- promise There are three states :pending、rejected、fulfilled
- Only results of asynchronous operations , You can decide which state you are in , No other operation can change this state
- Once the status changes , It won't change ,
Promise
Object state changes , There are only two possibilities : frompending
Turn intofulfilled
And from thepending
Turn intorejected
One 、promise.all
characteristic :
- Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following
Promise.resolve
Method , Convert parameter to Promise example , Further processing ) - The return value is promise example
- If it all works , The status changes to resolved, And the return value forms an array and is passed to the callback
- Whenever there is a failure , The status changes to rejected, And will error Return to callback
- The return result is strictly in accordance with the incoming promise Sequential return
Code :
function all(iterable) {
return new Promise((resolve, reject) => {
let result = []; // Store results
let count = 0; // There are several records resolve
// empty
if (!iterable || iterable.length === 0) {
resolve([]);
return;
}
for (let i = 0; i < iterable.length; i++) {
let promise = iterable[i];
// If not promise example , It turns into promise
if (!(promise instanceof Promise)) {
promise = Promise.resolve(promise);
}
promise.then(
(value) => {
result[i] = value;
count++;
if (count === iterable.length) {
resolve(result);
}
}
).catch(
(err) => {
reject(err);
}
);
}
});
}
verification :
// There is one reject verification
let p1 = Promise.resolve(1),
p2 = Promise.reject(2),
p3 = Promise.resolve(3);
all([p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
// 2 err
// All of them resolve verification
let p1 = Promise.resolve(1),
p2 = Promise.resolve(2),
p3 = Promise.resolve(3);
all([p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
// [ 1, 2, 3 ] res
// There are not promise verification
let p1 = Promise.resolve(1),
p2 = Promise.resolve(2),
p3 = Promise.resolve(3);
all([0,p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
// [ 0, 1, 2, 3 ] res
Two 、promise.race
race It's a game 、 The meaning of competition , So as the name suggests , It's about who's fast , Just go back to who .
characteristic :
- Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following
Promise.resolve
Method , Convert parameter to Promise example , Further processing ) - The return value is promise example
- There is an instance of changing state ( Whether it's resolve still reject), ends , And return the result of this instance to the callback function
Code :
function race(iterable) {
return new Promise((resolve, reject) => {
// empty
if (!iterable || iterable.length === 0) {
resolve([]);
return;
}
for (let i = 0; i < iterable.length; i++) {
let promise = iterable[i];
// If not promise example , It turns into promise
if (!(promise instanceof Promise)) {
promise = Promise.resolve(promise);
}
promise.then(
(value) => {
resolve(value);
}
).catch(
(err) => {
reject(err);
}
);
}
});
}
verification :
// All successfully verified
let p1 = Promise.resolve(1),
p2 = Promise.resolve(2),
p3 = Promise.resolve(3);
race([p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
// 1 res
// There are failed verifications
let p1 = Promise.reject(1),
p2 = Promise.reject(2),
p3 = Promise.resolve(3);
race([p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
// 1 res
3、 ... and 、promise.allSettled
characteristic :
- Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following
Promise.resolve
Method , Convert parameter to Promise example , Further processing ) - The return value is promise example
- It ends only when all results are returned ( Whether it's resolve still reject), Return all results as an array , Each result is an object , contain value and status,ES2020 introduce
[{ status: "rejected", reason: error1 }, { status: "fulfilled", value: 1 }];
Code :
// Process the returned result in the specified format
const formatSettledResult = (success, value) =>
success
? { status: "fulfilled", value }
: { status: "rejected", reason: value };
function allSettled(iterable) {
return new Promise((resolve, reject) => {
let len = iterable.length;
// empty
if (!iterable || len === 0) {
resolve([]);
return;
}
let result = []; // Save the finished results
for (let i = 0; i < len; i++) {
let promise = iterable[i];
// If not promise example , It turns into promise
if (!(promise instanceof Promise)) {
promise = Promise.resolve(promise);
}
promise.then(
(value) => {
result[i] = formatSettledResult(true, value);
if (result.length === len) {
resolve(result);
}
}
).catch(
(err) => {
result[i] = formatSettledResult(false, err);
if (result.length === len) {
resolve(result);
}
}
);
}
});
}
verification :
// verification
let p1 = Promise.reject(1),
p2 = Promise.reject(2),
p3 = Promise.resolve(3);
allSettled([p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
/*[
{ status: 'rejected', reason: 1 },
{ status: 'rejected', reason: 2 },
{ status: 'fulfilled', value: 3 }
] res
*/
Four 、promise.any
And promise.all Just the opposite
characteristic :
- Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following
Promise.resolve
Method , Convert parameter to Promise example , Further processing ) - The return value is promise example
- As long as one of the parameter instances becomes
fulfilled
state , The packaging instance will becomefulfilled
state ; If all parameter instances becomerejected
state , The packaging instance will becomerejected
state , And return the result as an array - Not because of one Promise become
rejected
State and end
Code :
function any(iterable) {
return new Promise((resolve, reject) => {
let len = iterable.length;
// empty
if (!iterable || len === 0) {
resolve([]);
return;
}
let result = []; // preservation rejected Result
for (let i = 0; i < len; i++) {
let promise = iterable[i];
// If not promise example , It turns into promise
if (!(promise instanceof Promise)) {
promise = Promise.resolve(promise);
}
promise.then(
(value) => {
resolve(value);
}
).catch(
(err) => {
result[i] = err;
if (result.length === len) {
reject(result);
}
}
);
}
});
}
verification :
// verification
let p1 = Promise.reject(1),
p2 = Promise.reject(2),
p3 = Promise.reject(3);
any([p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
// [ 1, 2, 3 ] err
// verification
let p1 = Promise.reject(1),
p2 = Promise.reject(2),
p3 = Promise.resolve(3);
any([p1,p2,p3]).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err, 'err')
});
// 3 res
summary : That's all , Is it not difficult at all !! Just know everyone API Characteristics , It can be easily realized , But this is only a simple version , Poor fault tolerance , For reference only .
边栏推荐
- 千人规模互联网公司研发效能成功之路
- Unity 贴图自动匹配材质工具 贴图自动添加到材质球工具 材质球匹配贴图工具 Substance Painter制作的贴图自动匹配材质球工具
- Learning and using vscode
- Completion report of communication software development and Application
- College entrance examination composition, high-frequency mention of science and Technology
- Vxlan static centralized gateway
- @What happens if bean and @component are used on the same class?
- 数据库系统原理与应用教程(009)—— 概念模型与数据模型
- Sonar:Cognitive Complexity认知复杂度
- 【统计学习方法】学习笔记——逻辑斯谛回归和最大熵模型
猜你喜欢
数据库系统原理与应用教程(011)—— 关系数据库
【PyTorch实战】图像描述——让神经网络看图讲故事
Tutorial on the principle and application of database system (011) -- relational database
File upload vulnerability - upload labs (1~2)
The hoisting of the upper cylinder of the steel containment of the world's first reactor "linglong-1" reactor building was successful
Several methods of checking JS to judge empty objects
idm服务器响应显示您没有权限下载解决教程
盘点JS判断空对象的几大方法
Sort out the garbage collection of JVM, and don't involve high-quality things such as performance tuning for the time being
【统计学习方法】学习笔记——提升方法
随机推荐
数据库系统原理与应用教程(007)—— 数据库相关概念
SQL Lab (32~35) contains the principle understanding and precautions of wide byte injection (continuously updated later)
Review and arrangement of HCIA
什么是局域网域名?如何解析?
让数字管理好库存
顶级域名有哪些?是如何分类的?
<No. 8> 1816. Truncate sentences (simple)
Simple network configuration for equipment management
数据库系统原理与应用教程(009)—— 概念模型与数据模型
About sqli lab less-15 using or instead of and parsing
防红域名生成的3种方法介绍
Utiliser la pile pour convertir le binaire en décimal
<No. 9> 1805. Number of different integers in the string (simple)
Tutorial on principles and applications of database system (010) -- exercises of conceptual model and data model
Experiment with a web server that configures its own content
Inverted index of ES underlying principle
全球首堆“玲龙一号”反应堆厂房钢制安全壳上部筒体吊装成功
File upload vulnerability - upload labs (1~2)
Tutorial on the principle and application of database system (011) -- relational database
VSCode的学习使用