当前位置:网站首页>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 .
边栏推荐
- TypeScript 接口继承
- Attack and defense world - PWN learning notes
- idm服务器响应显示您没有权限下载解决教程
- 什么是ESP/MSR 分区,如何建立ESP/MSR 分区
- Sign up now | oar hacker marathon phase III midsummer debut, waiting for you to challenge
- Baidu digital person Du Xiaoxiao responded to netizens' shouts online to meet the Shanghai college entrance examination English composition
- Zhimei creative website exercise
- Up meta - Web3.0 world innovative meta universe financial agreement
- SQL Lab (46~53) (continuous update later) order by injection
- Simple network configuration for equipment management
猜你喜欢
H3C HCl MPLS layer 2 dedicated line experiment
Introduction and application of smoothstep in unity: optimization of dissolution effect
wallys/Qualcomm IPQ8072A networking SBC supports dual 10GbE, WiFi 6
【PyTorch实战】用PyTorch实现基于神经网络的图像风格迁移
小红书微服务框架及治理等云原生业务架构演进案例
[statistical learning methods] learning notes - improvement methods
111. Network security penetration test - [privilege escalation 9] - [windows 2008 R2 kernel overflow privilege escalation]
An error occurred when vscade tried to create a file in the target directory: access denied [resolved]
Tutorial on principles and applications of database system (007) -- related concepts of database
111.网络安全渗透测试—[权限提升篇9]—[Windows 2008 R2内核溢出提权]
随机推荐
Dialogue with Wang Wenyu, co-founder of ppio: integrate edge computing resources and explore more audio and video service scenarios
Solve server returns invalid timezone Go to ‘Advanced’ tab and set ‘serverTimezone’ property manually
wallys/Qualcomm IPQ8072A networking SBC supports dual 10GbE, WiFi 6
SQL head injection -- injection principle and essence
Ctfhub -web SSRF summary (excluding fastcgi and redI) super detailed
全球首堆“玲龙一号”反应堆厂房钢制安全壳上部筒体吊装成功
Tutorial on principles and applications of database system (009) -- conceptual model and data model
解密GD32 MCU产品家族,开发板该怎么选?
Sonar:Cognitive Complexity认知复杂度
消息队列消息丢失和消息重复发送的处理策略
ENSP MPLS layer 3 dedicated line
Xiaohongshu microservice framework and governance and other cloud native business architecture evolution cases
Vxlan static centralized gateway
Customize the web service configuration file
108. Network security penetration test - [privilege escalation 6] - [windows kernel overflow privilege escalation]
【PyTorch实战】用RNN写诗
[pytorch practice] image description -- let neural network read pictures and tell stories
密码学系列之:在线证书状态协议OCSP详解
开发一个小程序商城需要多少钱?
Introduction to three methods of anti red domain name generation