手写Promise的静态方法

1.手写请求超时方法

let request = ajax('./api');
let timeout = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        reject('timeout');
    },5000)
})

Promise.race([
    request,
    timeout
]).then((res)=>{
    console.log(res);
}).catch((err)=>{
    console.log(err);
})

2.实现一个Promise.all

Promise.myall = (arr) => {
    console.log('hello');
    let res = new Array(arr.length);
    let cnt = 0;// 成功的数量
    return new Promise((resolve,reject) => {
        arr.forEach((item,index) => {
            let i = index;
            Promise.resolve(item).then(value => {
                res[i] = value;
                cnt++;
                if(cnt === arr.length){
                    resolve(res);
                }
            }).catch(err => {
                reject(err);
            })
        })
    })
}

Promise.first

顾名思义就是返回第一个被resolve的promise,参数是一个promise数组,如果全都被reject的话就返回reject,Promise概念熟悉的话就非常简单:

Promise.first = function(list) {
    let count = 0

    return new Promise((resolve, reject) => {
        try {
            list.forEach(p => {
                p.then(resolve, () => {
                    ++count
                    count === list.length && reject(`all promises had been rejected`)
                })
            })
        } catch (e) {
            reject(e)
        }
    })
}

Promise.last

字面意思就是返回最后一个resolve掉的promise,同样也是接受一个promise数组,全被reject就返回reject信息,不过为了记录最后一个被resolve的结果,需要添加一个临时变量,代码相对first方法繁琐一点,then中两个函数都要判断:

Promise.last = function(list) {
    const len = list.length
    let result = null
    let count = 0

    return new Promise((resolve, reject) => {  
        try {
            for (let i = 0; i < len; ++i) {   
                list[i].then( data => {
                    count++
                    result = data
                    count === len ? resolve(result) : ''
                }, () => {
                    count++
                    count === len ? result === null ? reject(`all promises had been rejected`) : resolve(result): ''
                })
            }
        } catch (e) {
            reject(e)
        }
    })
}

你可能感兴趣的:(react,javascript,前端,es6)