Promise and Reduce

Time:2020-7-20

Promise organization code

Promise

Ajax version promise, to solve the problem of asynchronous.

ajax1().then(ajax2).then(ajax3).then(()=>{})

Comments: it always makes people feel that promise exists for Ajax

Some people cleverly encapsulate promise on the pop-up components.

//Callback mode
Alert ('are you sure you want to delete this data ', () = >{
        console.log ('deleted successfully')
    },()=>{
        console.log ('undelete ')
    })
    
//Promise, meaning seems a little bit small!!!
alert('您确定要删除这条数据吗').then(()=>console.log ('deleted successfully')).catch(()=>console.log ('undelete '))

Comments: it’s a good idea, and finally broke through Ajax. But if you use it in this way, I think it’s a bit “mystifying”

I think that the scenarios used by promise should tend to be a little complicated

function enSureDelete(){
    return new Promise((resolve,reject)=>{
        Alert ('are you sure you want to add this user ', () = > resolve, () = > reject)
    })
}
function validateUser(){
    return new Promise((resolve,reject)=>{
        let username=$('id').val()
        if(username){
            resolve()
        }else{
            Reject ({MSG: 'cannot be empty'})
        }
    })  
}
function submitAPi(){
    return new Promise((resolve,reject)=>{
        $.ajax({success:resolve,error:reject})
    })
}
$(button).click(()=>{
  enSureDelete().then(validateUser).then(submitAPi).catch(({msg})=>msg&&Tip(msg))
})

Comments: I feel one-sided to think that the purpose of using promise is to use its then and catch, and to run for its multiple then and a catch. Only in this way can it prevent the code

    $p().then().then().then().catch()

Promise && reduce

reduce

Many people think that reduce is a natural combination of things that are rarely used or even not used in projects. If sort > Filter > sort > Filter > sort > Filter > sort > Filter > sort > Filter > Filter > sort > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter > Filter >

let a=[1,2,3,4]
let sum=a.reduce((a,b)=>a+b,0)

This example is no stranger. Think about it. Even if there are such requirements in the project, they will normally be accumulated for / map / foreach. As soon as the reduce feeling is created, it has been out

But reduce is the toughest

For example, a friend who has written a crawler must be familiar with the following code, whether you are reading other people’s code or writing your own code

let page=0,total=100
function runTask(page){
    request(`//www.xxx.com/${page}.html`).then(()=>{
        //todo
        //....
        page++
        if(page<total){
            runTask(page)
        }
    })
}
runTask(0)

Start to enlarge your moves

let arr=[]
for(let i=0;i<100;i++){
    arr.push(request(`//www.xxx.com/${page}.html`))
}
let $p=arr.reduce((a,b)=>{
return a.then(()=>{
        return b().then(()=>{
                //todo
                return data
        })
    })
},Promise.resolve())

$p.then().catch()

Of course, I can also optimize, to 10 concurrent

let arr={}
for(let i=0;i<100;i++){
    let a=parseInt(1/10)
    arr[a]=arr[a]||[]
    arr[a].push(request(`//www.xxx.com/${page}.html`))
}
arr=Array.from(arr)
let $p=arr.reduce((a,b)=>{
return a.then(()=>{
    return Promise.all(b).then(()=>{...})
})
},Promise.resolve())

$p.then().catch()

Another wave is about validation

const Rules={
    Required (MSG) {// verify that the field is empty
        return(value){
            if(value){
                return {succ:true}
            }else{
                return {succ:false,msg}
            }
        }
    },
    ...
}
Const validates = [// construct validation rules
            { fn:  Rules.Required ('please fill in a valid name! '), value: $('name').val() },
            { fn:  Rules.Illegal ('name ', {Min: 2, Max: 11}), value: $('name'). Val()},
            { fn:  Rules.Required ('please fill in valid ID card! '), value: $('shenfenzheng').val() },
            { fn: Rules.Certificate(_certNo), value: $('shenfenzheng').val() }
        ]
        const $P = validates.reduce((p, rule) => {
            return p.then(() => {
                return new Promise((resolve, reject) => {
                    let _R = rule.fn(rule.value)
                    if (_R.succ) {
                        resolve()
                    } else {
                        reject(_R)
                    }
                })
            })
        }, Promise.resolve())

        $P.then(() => {
            return $.ajax().then(()=>{//todo})
        }).catch(err => Toast.info(err.msg))