当前位置:网站首页>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
边栏推荐
- vue--vuerouter缓存路由组件
- 9、智慧交通项目(2)
- How about opening an account at Guojin securities? Is it safe?
- Let torch cuda. is_ Experience of available() changing from false to true
- [ten thousand words summary] starting from the end, analyze in detail how to fill in the college entrance examination volunteers
- Detailed explanation of browser storage methods: the origin and difference of cookies, localstorage and sessionstorage
- 深层次安全定义剖析及加密技术
- RSA encryption and decryption details
- idea中文插件chinese(simplified) language pack
- 深入理解MySQL锁与事务隔离级别
猜你喜欢

并发之线程安全

halcon之区域:多种区域(Region)特征(5)

Discussion and generation of digital signature and analysis of its advantages

Bayesian network explanation

Vue--vuerouter cache routing component

properties文件乱码

Vscode usage - Remote SSH configuration description

一起备战蓝桥杯与CCF-CSP之大模拟炉石传说

LeetCode——226. 翻轉二叉樹(BFS)

wechat_ Solve the problem of page Jump and parameter transfer by navigator in wechat applet
随机推荐
js强制转换
sparksql如何通过日期返回具体周几-dayofweek函数
How sparksql returns a specific day of the week by date -dayofweek function
清华&商汤&上海AI&CUHK提出Siamese Image Modeling,兼具linear probing和密集预测性能!
Plt How to keep show() not closed
The king of Internet of things protocol: mqtt
Synchronized description of concurrency
【万字总结】以终为始,详细分析高考志愿该怎么填
Knapsack problem with dependency
How about opening a flush account? Is it safe? How to open a stock trading account
10 cloud security best practices that enterprises need to know
next(iter(dataloader))的一点点体会
#26class中get和set设置
数据加密标准(DES)概念及工作原理
properties文件乱码
vutils.make_grid()与黑白图像有关的一个小体会
vutils. make_ A little experience of grid () in relation to black and white images
pycharm的plt.show()如何保持不关闭
Li Kou daily question - day 28 -566 Reshape matrix
非对称密码体制详解