当前位置:网站首页>Handwritten promise all
Handwritten promise all
2022-06-26 17:58:00 【Dandan's servant】
promise.all In daily projects, we often encounter , Today we write promise.all This method , And explore the details .
Let's start with a few demo
const demo1 = new Promise((resolve, reject) =>{
setTimeout(() => {
resolve(1)
}, 1000)
})
const demo2 = new Promise((resolve, reject) =>{
setTimeout(() => {
resolve(2)
}, 2000)
})
const demo3 = new Promise((resolve, reject) =>{
setTimeout(() => {
resolve(3)
}, 3000)
})
const demo4 = new Promise((resolve, reject) => {
setTimeout(() =>{
reslove(4)
}, 4000)
})
To begin
In the first step, we should first think about promise.all It can be called in a chain , Then the internal must return a promise object .
function myPromiseAll(promiseArr) {
return new Promise(resolve, reject => {
···
})
}
The second step is to judge the parameters . Any method should be thought of at the beginning , Avoid other errors caused by late parameter types .
function myPromiseAll(promiseArr) {
return new Promise(resolve, reject => {
if(Array.isArray(promiseArr)) {
······
}else {
throw new Error(' Please pass in an array as a parameter ')
}
})
}
The third step is to traverse the array , At this time, you should think about whether the elements in the array are not one promise What about objects? ? Maybe someone will if Judge , have access to instanceof Or omnipotent Object.prototype.toString.call(), But there is a simpler way , It's direct use of Promise.resolve() The wrapping element will automatically promise The element becomes a promise object .
function myPromiseAll(promiseArr) {
return new Promise(resolve, reject => {
if(Array.isArray(promiseArr)) {
const len = promiseArr.length
for(let i = 0; i < len; i ++) {
Promise.resolve(promiseArr[i]).then(res => {
······
}).catch(err => {
reject(err)
})
}
}else {
throw new Error(' Please pass in an array as a parameter ')
}
})
}
Step four , Since the returned result is an array, we should think of the need to create an array to save the results . At this time, there will be the easiest places to make mistakes , That's it Array order , We will find the official promise.all The order of the returned array elements is passed in promise The order of array parameters . direct push The execution time may be different, so push The timing of entering the result array is different , At this time, you need to use array subscript to assign values , Finally, judge when to end the judgment , That is when the length of the result array is equal to the parameter .
function myPromiseAll(promiseArr) {
return new Promise((resolve, reject) => {
if(Array.isArray(promiseArr)) {
const len = promiseArr.length
let resArr = []
for(let i = 0; i < len; i ++) {
Promise.resolve(promiseArr[i]).then(res => {
resArr[i] = res
if(resArr.length === len) {
resolve(resArr)
}
}).catch(err => {
reject(err)
})
}
}else {
throw new Error(' Please pass in an array as a parameter ')
}
})
}
Step five , People feel that this is the end ? If you test, you will find , above promise.all Method execution myPromiseAll([demo1, demo2, demo3, demo4]) There is nothing wrong with that , But the order of this parameter changes according to the increasing order , That is to say, the order of their execution is consistent with the order of their parameters , If we replace the order , such as demo4, demo1, demo2, demo3 You will find that the first result of the array is null (empty), That is to say, the returned result is a scarce array . That is because the first parameter has the longest timing time , So it will be executed at the end , When executed demo3 When ,i Is equal to 3 了 , When an array is assigned with a subscript , Will change the length of the array , Although sometimes the subscript value is empty (empty), So it's done resolve, But this is demo4 It's not implemented , So it will cause the lack of results . At this time, we need an intermediate number to record how many parameters we have executed .
function myPromiseAll(promiseArr) {
return new Promise((resolve, reject) => {
if(Array.isArray(promiseArr)) {
const len = promiseArr.length
let resArr = []
let num = 0
for(let i = 0; i < len; i ++) {
Promise.resolve(promiseArr[i]).then(res => {
num ++
resArr[i] = res
if(num === len) {
resolve(resArr)
}
}).catch(err => {
reject(err)
})
}
}else {
throw new Error(' Please pass in an array as a parameter ')
}
})
}
In the end, it's done !
Pay attention to the summary :
- Note the type of parameter
- Note that the elements in the parameter array may not be promise object
- Note that success is the order of results returned
边栏推荐
- Leetcode daily [2022 - 02 - 16]
- Regular match same character
- 二分查找-2
- JS cast
- halcon之区域:多种区域(Region)特征(5)
- Tencent qianzhiming: Exploration and application of pre training methods in information flow business
- [QNX] Command
- The difference between round and truncate in SQL (round or truncate)
- MySQL add column failed because there was data before, not null by default
- in和exsits、count(*)查询优化
猜你喜欢

RSA concept explanation and tool recommendation - LMN

并发之Synchronized说明

Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance!

RuntimeError: CUDA error: out of memory自己的解决方法(情况比较特殊估计对大部分人不适用)

9、智慧交通项目(2)

LeetCode——226. 翻轉二叉樹(BFS)
![[uniapp] the uniapp mobile terminal uses uni Troubleshooting of navigateback failure](/img/26/da00e70d0955bcdef3362474bc5fc7.png)
[uniapp] the uniapp mobile terminal uses uni Troubleshooting of navigateback failure

数字签名标准(DSS)

vutils.make_grid()与黑白图像有关的一个小体会

Detailed explanation of asymmetric cryptosystem
随机推荐
Lm06 the mystery of constructing the bottom and top trading strategy only by trading volume
Regular match same character
Runtimeerror: CUDA error: out of memory own solution (it is estimated that it is not applicable to most people in special circumstances)
【Unity】在Unity中使用C#执行外部文件,如.exe或者.bat
DoS及攻击方法详解
Comp281 explanation
Using redis for user access data statistics hyperloglog and bitmap advanced data types
No manual prior is required! HKU & Tongji & lunarai & Kuangshi proposed self supervised visual representation learning based on semantic grouping, which significantly improved the tasks of target dete
[buuctf.reverse] 126-130
[recommendation system learning] recommendation system architecture
Leetcode daily [2022 - 02 - 16]
Synchronized description of concurrency
wechat_微信小程序中解决navigator进行页面跳转并传递参数问题
10 cloud security best practices that enterprises need to know
丰富专业化产品线, 江铃福特领睿·极境版上市
【uniapp】uniapp手机端使用uni.navigateBack失效问题解决
同花顺开户怎么样安全吗?怎么炒股开户
sql中ROUND和TRUNCATE的区别(四舍五入还是截取小数点后几位)
pycharm的plt.show()如何保持不关闭
股票开账户如何优惠开户?现在在线开户安全么?