当前位置:网站首页>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 .
边栏推荐
- Using swiper to realize seamless rotation of multiple slides
- It's an artifact to launch a website in a few minutes
- Assemble relevant knowledge points of flag bit (connected)
- 关于数据在内存中存储的相关例题
- Sword finger offer day 2 linked list (simple)
- C# 切换中英文输入法
- 1024 hydrology
- 解析數倉lazyagg查詢重寫優化
- 坡道带来的困惑
- Shenzhen mintai'an intelligent second side_ The first offer of autumn recruitment
猜你喜欢

Detailed explanation of string operation functions and memory functions

揭秘GaussDB(for Redis):全面对比Codis

Pointer, it has to say that the subject

解析數倉lazyagg查詢重寫優化

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

leetcode:剑指 Offer II 091. 粉刷房子【二维dp】

Serevlt初识

Maui's learning path (II) -- setting

Drago Education - typescript learning

Sword finger offer II 032 Effective anagrams
随机推荐
KDD 2022 | GraphMAE:自监督掩码图自编码器
Implementation of a small book system
Summer Ending
关于数据在内存中的存储下
康威定律,作为架构师还不会灵活运用?
Using swiper to realize seamless rotation of multiple slides
初始c语言的知识2.0
Golang keyboard input statement scanln scanf code example
爱可可AI前沿推介(6.25)
OpenStack-----Nova源码分析之创建虚拟机
leetcode:918. Maximum sum of circular subarray [reverse thinking + maximum subarray sum]
Sword finger offer day 1 stack and queue (simple)
KVM 脚本管理 —— 筑梦之路
Confusion caused by the ramp
golang键盘输入语句scanln scanf代码示例
Assemble relevant knowledge points of flag bit (connected)
LeetCode链表题解技巧归纳总结
Capabilities required by architects
數據在內存中的存儲相關內容
Solution to Nacos' failure to modify the configuration file mysql8.0