1. [‘ t? : n

2. (ali) promise. Then () If there are two parameters followed by catch, which one does reject go? From a code point of view.

let p1 = new Promise( (resolve, reject) = > {
    console.log('there is no resolve');
    reject('reject throws an error ')
}).then(res= > {
    console.log('then first callback function ', res);
}, rea= > {
    console.log('then second callback function ', rea);
}).catch(err= > {
    console.log('catch caught', err);
})
/ / not resolve
//then the second callback reject throws an error
Copy the code

Conclusion: If promise.then () has two arguments followed by catch,reject takes the second callback of then.

3.(Tencent) Priority of Promise and async/await

4. Handwritten Promises are easy to implement

const PENDING = 'PENDING',
      FULFILLED = 'FULFILLED',
      REJECTED = 'REJECTED';


class myPromise {
    constructor(executor) {
        this.status = PENDING;
        this.value = undefined;
        this.reason = undefined;
        this.onResolveCallbacks = [];
        this.onRejectedCallbacks = [];
        const resolve = (value) = > {
            if (this.status === PENDING) {
                this.status = FULFILLED;
                this.value = value;
                this.onResolveCallbacks.forEach((fn) = > fn())
            }
        }
        const reject = (reason) = > {
            if (this.status === PENDING) {
                this.status = REJECTED;
                this.reason = reason;
                this.onRejectedCallbacks.forEach((fn) = > fn())
            }
        }
        try { Throw errors in instantiated promises into reject
            executor(resolve, reject);
        } catch(e) { reject(e); }}then(onFulfilled, onRejected) {
        if (this.status === FULFILLED) {
            onFulfilled(this.value);
        }
        if (this.status === REJECTED) {
            onRejected(this.reason);
        }
        if (this.status === PENDING) {
            // Handle asynchronous function subscriptions
            this.onResolveCallbacks.push(() = > {
                onFulfilled(this.value);
            })
            this.onRejectedCallbacks.push(() = > {
                onRejected(this.value); })}}}Copy the code

5. The code implements Promise serial.

function runPromiseByQueue(promises) {
  promises.reduce(
    (previousPromise, nextPromise) = > previousPromise.then(() = > nextPromise()),
    Promise.resolve()
  )
}

const createPromise = (time, id) = > () = > {
  new Promise(resolve= > {
    setTimeout(() = > {
      console.log("promise", id);
      resolve();
    }, time)
  })
}

runPromiseByQueue([
  createPromise(3000.1),
  createPromise(2000.2),
  createPromise(1000.3)])Copy the code

6. The code implements promise.all.

Promise.all =  function(promises) {
    // Promises are iterable, omit argument validity check
    return new Promise((resolve, reject) = > {
        // array. from converts an iterable to an Array
        promises = Array.from(promises);
        if(promises.length === 0) {
            resolve([]);
        } else {
            let result = [];
            let index = 0;
            for(let i = 0; i < promises.length; i++) {
                // Consider whether I is a thenable object or a normal value
                Promise.resolve(promises[i]).then(data= > {
                    result[i] = data;
                    if(++index === promises.length) {
                        // This is a big pity. // All promises will become a big pityresolve(result); }},err= > {
                    reject(err);
                    return; })}}})}Copy the code

7. (Headline) Implement a Promise.allSettled with Promise.all

Promise.allSettled = function(promises) {
    return Promise.all(
    	Array.from(promises).map(p= > Promise.resolve(p).then(
        	res= > {
                return {
                    status: 'fulfilled'.value: res
                }
            },
            e= > {
                return {
                    status: 'rejected'.reason: e
                }
            }
        ))
    )
}
Copy the code