preface
Personal summary, for reference only.
Interviewer: Do you know Promise? Do you use it a lot?
If you say you know about it and use it A lot, the interviewer will not ask you to write the Promise/A+ specification by hand, because the interview usually takes about an hour, and the handwritten Promise/A+ will take A long time; So you might want to write the Promise’s static methods by hand.
Promise.all()
Interviewer: Do you know promise.all?
You might answer: promise. all receives an array of promises.
At this point, the interviewer asked back: Was the array really full of promises?
In the face of the interviewer’s questioning, you might respond: It’s not all promises. It can also be constants.
Interviewer: How is it being implemented?
Your answer: The result will be returned only after all promises have been executed.
Interviewer: What if one of them fails?
Your answer: It will be caught on catch.
The interviewer then asked, “Will anything else be done?”
You probably won’t at this point. The answer is yes, because promises are executed when they are instantiated; .then() is only used to see the result.
} const p1 = new Promise((res, rej) => {setTimeout(() => {res('p1')}, 1000) }) const p2 = new Promise((res, rej) => { setTimeout(() => { res('p2') }, 2000) }) const p3 = new Promise((res, rej) => { setTimeout(() => { res('p3') }, 3000) }) const test = PromiseAll([p1, p2, p3]) .then(res => console.log(res)) .catch(e => console.log(e)) console.log(test);Copy the code
Handwritten code pits
1. Many people don’t know they need to return onePromiseObject,
Return new Promise((resolve, reject) => {})}Copy the code
2. It is better to check whether the parameters passed in are arrays.
Return new Promise((resolve, reject) => {if(! Array.isarray (promiseArr)) {// Reject (new Error(' Reject! ')) } const res = [] for(let i = 0; i < promiseArr.length; i++) { } }) }Copy the code
3. There are many people who judge promises and constants separately in arrays, butIt’s going to get out of order
Return new Promise((resolve, reject) => {if(! Array.isarray (promiseArr)) {// Reject (new Error(' Reject! ')) } const res = [] for(let i = 0; i < promiseArr.length; i++) { const isPromise = Object.prototype.toString.call(promiseArr[i] === '[Object Promise]') // if(isPromise) { // If (result => res.push(result)) // else {// res.push(result) [I]) //} else {// res.push(result) [I]) //} // Promise.resolve(promiseArr[i]).then(value => { res.push(value) if (res.length === promiseArr.length) { resolve(res) } }) }})}Copy the code
The optimized answer
Return new Promise((resolve, reject) => {if (! Array.isarray (promiseArray)) {// Reject (new Error(' The argument is not an Array! '))} const res = [] const counter = 0 i < promiseArr.length; Resolve (promise.resolve (promiseArr[I]).then(value => {counter++ promiseArr.length) { resolve(res) } }).catch(e => reject(e)) } }) }Copy the code