[Front-end interview questions] Write a Promise.all method (recommended collection)

[Front-end interview questions] What is the use of Promise (asynchronous programming, callback hell) icon-default.png?t=LA92https://blog.csdn.net/weixin_46318413/article/details/122027650 ?

The Promise.all() method receives an input of a promise's iterable type (Note: Array, Map, and Set are all ES6 iterable types), and returns only one Promise instance, and the result of the resolve callback of all promises in that input is an array . The resolve callback of this Promise is executed when all the resolve callbacks of the input promises have ended , or when there are no more promises in the input iterable. Its reject callback execution is that as long as the reject callback of any input promise is executed or the input is illegal, an error will be thrown immediately , and the rejection is the first thrown error message.

MDN_Promise.all()https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/allhttps://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Scenario 1: The resolve callback of all input promises has ended , and the callback of promise.all can be output

//定义p1是在1秒后执行结果为{name: 'dai'}的promise的对象
let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve({
            name: 'dai'
        });
    }, 1000);
})
//定义p2是在2秒后执行结果为222的promise的对象
let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(222);
    }, 2000);
})
//Promise.all() 方法接收一个promise的iterable类型,判断传入的每一个对象是否都成功并返回一个数组,否则会报错
//因为要等两个promise全部执行完才进行输出,由于p2需要两秒后执行,所以会在两秒后将两个执行结果一起输出
Promise.all([p1, p2]).then(res => {
    console.log(res);//输出为[{name:'dai'},222]
})

Scenario 2: As long as the reject callback of any input promise is executed, an error will be thrown immediately , and the first thrown error messagerejected

//定义p1是在1秒后执行结果为{name: 'dai'}的promise的对象
let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(111);
    }, 1000);
})
//定义p2是在2秒后执行结果为222的promise的对象
let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        reject(222);
    }, 2000);
})

Promise.all([p1, p2]).then((res) => {
    console.log(res)//报错输出111
})

How to write Promise.all function by hand?

//定义p1是在1秒后执行结果为{name: 'dai'}的promise的对象
let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve({
            name: 'dai'
        });
    }, 1000);
})
//定义p2是在2秒后执行结果为222的promise的对象
let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(222);
    }, 2000);
})

//手写一个promise.all
function myPromiseAll(lists) {
    return new Promise((resolve, reject) => {
        let resArr = [];//定义执行结果
        let n = 0;//判断是否全部
        lists.forEach(list => {
            list.then(item => {
                //把输入数组中的每一个promise的执行结果push到resArr中
                resArr.push(item);
                n++;
                //通过n判断是否执行结束
                if (n === lists.length) {
                    return resolve(resArr)
                }
            }, (reason) => {
                //如果遇到有一个reject,立马结束并输出第一个reject
                return reject(reason);
            })
        });
    })
}

//因为返回的是Promise对象,所以要通过then拿到执行结果
myPromiseAll([p1, p2]).then(res => {
    console.log(res)//输出[{name:'dai'},222]
})

The above is the mechanism and handwriting method of Promise.all.

I am the front-end Dai, a coder who will share the common problems in his usual projects and the knowledge of written test interviews with you on CSDN. I hope everyone can make progress together. Come on.

Guess you like

Origin blog.csdn.net/weixin_46318413/article/details/122023908#comments_20499161