preface
Promise is a new syntax for ES6 to handle asynchronous requests and solve the callback hell that used to happen without Promises. Several API, Promise Promise. Resolve, Promise. Reject, Promise. All, Promise. Race. We can use promise. all for multiple asynchronous processing, but promise. all will only call the success callback in.then if all promises are resolved. Reject (reject), reject (reject), reject (reject), reject (reject));
Open to
Let’s look at the use of promise.all.
Promise.all([Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)])
.then(res= > console.log(res),err=>console.log(err))
/ / [1, 2, 3]
Promise.all([Promise.reject(1), Promise.resolve(2), Promise.resolve(3)])
.then(res= > console.log(res),err=>console.log(err))
/ / 1
Copy the code
Promise.all is passed in as an array of Promise objects. The RES is printed when all of the promises in the array succeed, and err is printed when any promise fails.
We want to be able to print all of our information even if we fail. How do we do that? It’s easy to use.then because.then also returns a promise object, and either resolve or reject executes.then. When you return the Promise object, it becomes a REsovle state.
Promise.all([Promise.reject(1).then((res) = > ({ status: 'ok', res }), (err) => ({ status: 'not ok', err })),
Promise.resolve(2).then((res) = > ({ status: 'ok', res }), (err) => ({ status: 'not ok', err })),
Promise.resolve(3).then((res) = > ({ status: 'ok', res }), (err) => ({ status: 'not ok', err }))])
.then(res= > console.log(res),err=>console.log(err))
//[ {status: "not ok", err: 1},{status: "ok", res: 2},{status: "ok", res: 3}]
Copy the code
This prints out all the information, even if there is a reject state in promise.all.
Optimization of packaging
Now it’s kind of cumbersome, because every promise in every array has to write the same.then. We can separate out the dot then. Wrap it into a function, then use the map method to do each promise. then, and return the new array.
function handlePromise(promiseList) {
return promiseList.map(promise= >
promise.then((res) = > ({ status: 'ok', res }), (err) => ({ status: 'not ok', err }))
)
}
Copy the code
When you call promise.all like this, you can write:
Promise.all(handlePromise([Promise.reject(1),Promise.resolve(2),Promise.resolve(3)]))
.then(res= > console.log(res),err=>console.log(err))
Copy the code
Same effect.
We could even write a promise.allSettled method:
Promise.allSettled2 = function (promiseList) {
return Promise.all(handlePromise(promiseList))
}
Promise.allSettled2 ([Promise.reject(1),Promise.resolve(2),Promise.resolve(3)]).then(res= > console.log(res), err => console.log(err))
Copy the code
This is Promise’s new allSettled Api. It’s just not very compatible, but after reading this article, we can package our own Api to do the same thing. Finish scattering flowers.