当前位置:网站首页>Method for wrapping multiple promise instances into a new promise instance
Method for wrapping multiple promise instances into a new promise instance
2022-06-25 13:21:00 【acgCode】
Will be multiple Promise The example is packaged into a new Promise Example method
Promise Object provides many methods to implement multiple Promise Unified processing of instances , I will explain the common methods one by one below .
Promise.all()
Promise.all() When all Promise After the execution is completed, an array composed of all data is returned , If any Promise Failure , Directly returns the Promise Error messages for .
// Promise Pass parameter encapsulation
function test(arg) {
const p = new Promise((resolve, reject) => {
if (arg) {
resolve(`result is ${
arg}`);
} else if (arg === 0) {
throw new Error("result is 0");
} else {
reject("result is null");
}
});
return p;
}
// They all succeeded
Promise.all([test(1), test(2), test(4)])
.then((data) => console.log(data))
.catch((err) => console.error(err));
// test() reject
Promise.all([test(1), test(), test(0)])
.then((data) => console.log(data))
.catch((err) => console.error(err));
// test(0) Throw an exception
Promise.all([test(1), test(0), test()])
.then((data) => console.log(data))
.catch((err) => console.error(err));
The output is :
[ 'result is 1', 'result is 2', 'result is 4' ]
result is null
Error: result is 0
The test above Promise What happens if the instance calls back itself ?
// Promise Pass parameter encapsulation
function test(arg) {
const p = new Promise((resolve, reject) => {
if (arg) {
resolve(`result is ${
arg}`);
} else if (arg === 0) {
throw new Error("result is 0");
} else {
reject("result is null");
}
})
.then((result) => {
console.log(`Promise success: ${
result}`);
return result;
})
.catch((err) => {
console.error(`Promise error: ${
err}`);
return err;
});
return p;
}
Promise.all([test(1), test(), test(0)])
.then((data) => console.log(`all success: ${
data}`))
.catch((err) => console.error(`all fail: ${
err}`));
Promise.all([test(1), test(0), test()])
.then((data) => console.log(`all success: ${
data}`))
.catch((err) => console.error(`all fail: ${
err}`));
The output result is :
Promise success: result is 1
Promise success: result is 1
Promise error: result is null
Promise error: Error: result is 0
Promise error: Error: result is 0
Promise error: result is null
all success: result is 1,result is null,Error: result is 0
all success: result is 1,Error: result is 0,result is null
It can be seen from the above that ,Promise Will take the lead in handling callbacks by themselves , A failed callback will not break all The operation of , The mistakes here are taken as resolve Processed . So in the end all The successful callback method is called when .
Promise.allSettled()
Whether it's resolve still reject Will be carried out smoothly , And return to the successful callback processing . In the returned data ,status by fulfilled It means success , Corresponding value Is the data returned successfully ;status by rejected It means failure , Corresponding value Is a failure prompt .
const pAllSettled1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("1s up");
}, 1000);
});
const pAllSettled2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("2s up");
}, 2000);
});
const pAllSettled3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("3s up");
}, 3000);
});
Promise.allSettled([pAllSettled1, pAllSettled2, pAllSettled3])
.then((data) => console.log("success: " + JSON.stringify(data)))
.catch((err) => console.error("catch: " + err));
The output is :
success: [{
"status":"fulfilled","value":"1s up"},{
"status":"rejected","reason":"2s up"},{
"status":"fulfilled","value":"3s up"}]
But an exception interrupts all callbacks .
const pAllSettled1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("1s up");
}, 1000);
});
const pAllSettled2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("2s up");
}, 2000);
});
const pAllSettled3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("3s up");
}, 3000);
});
const pAllSettled4 = new Promise((resolve, reject) => {
setTimeout(() => {
throw new Error("x.5s up");
}, 2500);
});
Promise.allSettled([pAllSettled1, pAllSettled2, pAllSettled3, pAllSettled4])
.then((data) => console.log("success: " + JSON.stringify(data)))
.catch((err) => console.error("catch: " + err));
The output result is :
Error: x.5s up
Promise.race()
race As the name suggests, the method is “ competition ”, Regardless of success or failure , Deal with the one who finishes first .
const pRace1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("1s up");
}, 1000);
});
const pRace2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("2s up");
}, 2000);
});
Promise.race([
pRace1,
pRace2,
new Promise((resolve, reject) => {
setTimeout(() => {
reject("request timeout");
}, 500);
}),
])
.then((data) => console.log(`success: ${
data}`))
.catch((err) => console.error(`error: ${
err}`));
Promise.race([
pRace1,
pRace2,
new Promise((resolve, reject) => {
setTimeout(() => {
reject("request timeout");
}, 1500);
}),
])
.then((data) => console.log(`success: ${
data}`))
.catch((err) => console.error(`error: ${
err}`));
Promise.race([
pRace1,
pRace2,
new Promise((resolve, reject) => {
setTimeout(() => {
reject("request timeout");
}, 2500);
}),
])
.then((data) => console.log(`success: ${
data}`))
.catch((err) => console.error(`error: ${
err}`));
The output is :
error: request timeout
success: 1s up
success: 1s up
It can be seen from the above that , Who is the first to complete , Whoever calls back .
If in Promise There are exceptions in ?
const pRace1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("1s up");
}, 1000);
});
const pRace2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("2s up");
}, 2000);
});
Promise.race([
pRace1,
pRace2,
new Promise((resolve, reject) => {
setTimeout(() => {
throw new Error("game over");
}, 1500);
}),
])
.then((data) => console.log(`success: ${
data}`))
.catch((err) => console.error(`error: ${
err}`));
The output is :
success: 1s up
Error: game over
When the exception is in the other Promise Before that ?
Error: game over
So anomalies are thrown out , Everything will be thrown out . But we can also think of the exception as a reject, Even if the first one is abnormal , He won't be catch Capture , But it will also be recognized as the first callback , And lead to later Promise The callback of is no longer executed .
Promise.any()
As long as there is resolve Will return to the current resolve, Even if there is reject Or exceptions will not interrupt the search for success Promise .
because
anyThe method is ES2021 Introduced ,vscode Of Run Code The plug-in cannot run directly , So I used the method of page testing .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Promise Page Test of </title>
</head>
<body>
<script> const pAny1 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("1s up"); }, 1000); }); const pAny2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("2s up"); }, 2000); }); const pAny3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("3s up"); }, 3000); }); Promise.any([pAny1, pAny2, pAny3]) .then((data) => console.log(`success: ${
data}`)) .catch((err) => console.log(`err: ${
err}`)); </script>
</body>
</html>
The output result is :
success: 2s up
By the visible on ,pAny2 stay pAny3 Before resolve, meanwhile pAny1 although reject But it doesn't stop the following The success of Promise The callback .
although reject There will be no callback , Exceptions will still be catch Capture ?
const pAny1 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("1s up");
}, 1000);
});
const pAny2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("2s up");
}, 2000);
});
const pAny3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("3s up");
}, 3000);
});
const pAny4 = new Promise((resolve, reject) => {
setTimeout(() => {
throw new Error("x.5s up");
}, 1500);
});
Promise.any([pAny1, pAny2, pAny3, pAny4])
.then((data) => console.log(`success: ${
data}`))
.catch((err) => console.log(`err: ${
err}`));
The output is :

It can be seen from the above that , Exceptions do not affect others Promise The callback , And not by catch Capture processed .
I wonder if the exception is placed in a resolve Will it be thrown later ?
function test(arg, time) {
const p = new Promise((resolve, reject) => {
console.log(arg);
setTimeout(() => {
if (arg) {
resolve(`result is ${
arg}`);
} else if (arg === 0) {
throw new Error("result is 0");
} else {
reject("result is null");
}
}, time);
});
return p;
}
Promise.any([
test(null, 3000),
test(1, 1000),
test(2, 2000),
test(0, 1500),
])
.then((data) => console.log(`success: ${
data}`))
.catch((err) => console.log(`err: ${
err}`));
The output is :
thus it can be seen , Although only the first one will be returned resolve, But all Promise Are executed . Exceptions will not be catch Capture to .
边栏推荐
- [flask tutorial] flask development foundation and introduction
- 1251- client does not support authentication protocol MySQL error resolution
- leetcode:918. 环形子数组的最大和【逆向思维 + 最大子数组和】
- Introduction to mongodb chapter 01 introduction to mongodb
- 關於數據在內存中的存儲下
- 德国举行全球粮食安全团结会议
- C # switch between Chinese and English input methods
- Openstack learning notes -grace component insight
- 1024 hydrology
- [转]以终为始,详细分析高考志愿该怎么填
猜你喜欢

Confusion caused by the ramp

解析数仓lazyagg查询重写优化

关于一道教材题的讲解

Seven competencies required by architects

剑指 Offer II 032. 有效的变位词

. NET in China - What's New in . NET

Sword finger offer II 029 Sorted circular linked list

Sword finger offer II 028 Flatten multi-level bidirectional linked list

Which Chinese virtual human is better? Sullivan, IDC: Xiaobing Baidu Shangtang ranks in the first echelon

Django框架——缓存、信号、跨站请求伪造、 跨域问题、cookie-session-token
随机推荐
Summer Ending
Openstack -- creating virtual machines for Nova source code analysis
一篇文章讲清楚MySQL的聚簇/联合/覆盖索引、回表、索引下推
Download File blob transcoding
Implementation of a small book system
Sword finger offer day 2 linked list (simple)
À propos du stockage des données en mémoire
Sword finger offer II 032 Effective anagrams
Knowledge of initial C language 2.0
leetcode:918. 环形子数组的最大和【逆向思维 + 最大子数组和】
关于扫雷的简易实现
Some knowledge about structure, enumeration and union
Conway's law can not be flexibly applied as an architect?
[pit avoidance means "difficult"] to realize editable drag and drop sorting of protable
Custom vertical table
[pit avoidance means "difficult"] actionref current. Reload() does not take effect
关于一道教材题的讲解
Nova中的api
Django框架——缓存、信号、跨站请求伪造、 跨域问题、cookie-session-token
剑指 Offer II 025. 链表中的两数相加