Home >Web Front-end >JS Tutorial >Some common application scenarios of front-end Promise

Some common application scenarios of front-end Promise

hzc
hzcforward
2020-06-15 10:08:314431browse

This article will summarize the common application scenarios of Promise in our project development based on my own use of ES6 Promise. Of course, Promise may not be the only option, but as a qualified front-end developer, we need to understand it.

Promise.all


## Syntax: Promise.all (iterable)

Parameters: an iterable object, such as Array.

Return value:

  • If the passed iterable is empty, it is a Promise that has been resolved.


  • Promise.all([]).then(res=>{
        console.log(res)//[]
    })
  • Promise resolved asynchronously (if the passed Iterable does not contain a Promise). Note that Google Chrome 58 returns resolved promises in this case.

  • Promise.all([1,2,3]).then(res=>{
        console.log(res)//[1,2,3]
    })
  • This returned promise will be resolved/rejected asynchronously when all promises in the given iterable have resolved, or when any promise has been rejected (When the stack is empty)

    1. When all promises in the given iterable object have been resolved

  • let promise1 = new Promise((resolve,reject)=>{
        resolve(1)
    })
    let promise2 = new Promise((resolve,reject)=>{
        resolve(2)
    })
    
    Promise.all([promise1,promise2,3]).then(res=>{
        console.log(res)//[1,2,3]
    })
2. When all promises in the given iterable object When any promise is rejected

let promise1 = new Promise((resolve,reject)=>{
    resolve(1)
})
let promise2 = new Promise((resolve,reject)=>{
    reject(2)
})

Promise.all([promise1,promise2,3]).then(res=>{
    console.log(res)
}).catch(err=>{
    console.log(err)//2
})

Description:

This method is useful for aggregating the results of multiple promises. In ES6, multiple Promise.all asynchronous requests can be operated in parallel:

1. When all results are returned successfully, success is returned in the request order;

2. When there is a failure method, enter the failure method;

Application scenario 1 : Multiple request results are merged together

Detailed description: One page has multiple requests. We need all requests to return data before processing and rendering together

Thinking: If there are concurrent requests, the loading status of each request must be set separately. If there are multiple loadings, multiple loadings may overlap. The content displayed on the page will vary according to the speed of returning data according to the request, which is specifically reflected in the rendering process. In order to improve the user experience, we can use all requests to return data and then render them together. At this time, we turn off the separate loading setting of the request and summarize the request results through Promise.all. From the beginning to the end, we only set one loading.


//1.获取轮播数据列表
function getBannerList(){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve('轮播数据')
        },300)
    })
}

//2.获取店铺列表
function getStoreList(){
   return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve('店铺数据')
        },500)
    })
}

//3.获取分类列表
function getCategoryList(){
   return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve('分类数据')
        },700)
    })
}

function initLoad(){
    // loading.show() //加载loading
    Promise.all([getBannerList(),getStoreList(),getCategoryList()]).then(res=>{
        console.log(res)
        // loading.hide() //关闭loading
    }).catch(err=>{
        console.log(err)
        // loading.hide()//关闭loading
    })
}
//数据初始化    
initLoad()

Application Scenario 2: Merge request results and handle errors

Description: We need to handle the data rendering and error handling logic of a request separately , if there are multiple requests, we need to write

in multiple places. Thinking: Can we merge multiple requests together? Even if some requests fail, they will be returned to us. We only Just handle the data and error logic in one place.

//1.获取轮播图数据列表
function getBannerList(){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            // resolve('轮播图数据')
            reject('获取轮播图数据失败啦')
        },300)
    })
}

//2.获取店铺列表
function getStoreList(){
   return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve('店铺数据')
        },500)
    })
}

//3.获取分类列表
function getCategoryList(){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve('分类数据')
        },700)
    })
}

function initLoad(){
    // loading.show()
    Promise.all([
        getBannerList().catch(err=>err),
        getStoreList().catch(err=>err),
        getCategoryList().catch(err=>err)
    ]).then(res=>{
        console.log(res) // ["获取轮播图数据失败啦", "店铺数据", "分类数据"]
        
        if(res[0] == '轮播图数据'){
            //渲染
        }else{
            //获取 轮播图数据 失败的逻辑
        }
        if(res[1] == '店铺数据'){
            //渲染
        }else{
            //获取 店铺列表数据 失败的逻辑
        }
        if(res[2] == '分类数据'){
            //渲染
        }else{
             //获取 分类列表数据 失败的逻辑
        }
        
        // loading.hide()
    })
}

initLoad()

Sometimes the page hangs up, maybe because of an interface exception, or maybe it's just an insignificant interface that hangs up. So why does an interface hang up resulting in no data on the entire page? Promise.all tells us that if a promise in the parameter fails (rejected) and the callback of this instance fails (reject), the then method callback will no longer be executed. The above use case can solve this problem.

Application scenario 3: Verify whether multiple request results meet the conditions

Description: In a WeChat applet project, perform security verification of the input content of a form, call It is a method written by cloud functions. There are 7 fields in the form that need to be verified. They are all called by a content security verification interface. If all verification is passed, normal submission can be carried out

function verify1(content){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve(true)
        },200)
    })
}

function verify2(content){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve(true)
        },700)
    })
}

function verify3(content){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve(true)
        },300)
    })
}



Promise.all([verify1('校验字段1的内容'),verify2('校验字段2的内容'),verify3('校验字段3的内容')]).then(result=>{
    console.log(result)//[true, true, true]

    let verifyResult = result.every(item=>item)
    //验证结果
    console.log(verifyResult?'通过验证':'未通过验证')// 通过验证
}).catch(err=>{
    console.log(err)
})

Promise .race


Syntax: Promise.race(iterable)

Parameters: iterable iterable object, such as Array . Iterable.

Return value: The Promise.race(iterable) method returns a promise. Once a promise in the iterator is resolved or rejected, the returned promise will be resolved or rejected

DescriptionThe race function returns a Promise that will be fulfilled in the same way as the first passed promise. It can either resolve (resolve) or fail (rejects), depending on which of the two completed first.

If the passed iteration is empty, the returned promise will wait forever.

If the iteration contains one or more non-promise values ​​and/or resolved/rejected promises, Promise.race will resolve to the first value found in the iteration.

Application scenario 1: Image request timeout

//请求某个图片资源
function requestImg(){
    var p = new Promise(function(resolve, reject){
        var img = new Image();
        img.onload = function(){
           resolve(img);
        }
        //img.src = "https://b-gold-cdn.xitu.io/v3/static/img/logo.a7995ad.svg"; 正确的
        img.src = "https://b-gold-cdn.xitu.io/v3/static/img/logo.a7995ad.svg1";
    });
    return p;
}

//延时函数,用于给请求计时
function timeout(){
    var p = new Promise(function(resolve, reject){
        setTimeout(function(){
            reject('图片请求超时');
        }, 5000);
    });
    return p;
}

Promise
.race([requestImg(), timeout()])
.then(function(results){
    console.log(results);
})
.catch(function(reason){
    console.log(reason);
});

Application scenario 2: Request timeout prompt

Description: Sometimes, we are reading the news one second, and after entering the elevator the next second, you will be prompted on the mobile phone page that "the network is not good"

//请求
function request(){
    return new Promise(function(resolve, reject){
       setTimeout(()=>{
            resolve('请求成功')
       },4000)
    })
}

//请求超时提醒
function timeout(){
    var p = new Promise(function(resolve, reject){
        setTimeout(function(){
            reject('网络不佳');
        }, 3000);
    });
    return p;
}



Promise.race([
    request(),
    timeout()
])
.then(res=>{
    console.log(res)
}).catch(err=>{
    console.log(err)//网络不佳
})

Promise.prototype.then


Application scenario 1: The next request depends on the result of the previous request

描述:类似微信小程序的登录,首先需要 执行微信小程序的 登录 wx.login 返回了code,然后调用后端写的登录接口,传入 code ,然后返回 token ,然后每次的请求都必须携带 token,即下一次的请求依赖上一次请求返回的数据

function A(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve('B依赖的数据')
        },300)
    })
}
function B(prams){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve(prams + 'C依赖的数据')
        },500)
    })
}
function C(prams){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve(prams)
        },1000)
    })
}

//我们期望的是走 try ,由于A B C模拟的请求中都是没有reject,用 try catch 捕获错误
try{
    A().then( res=>B(res) ).then( res=>C(res) ).then( res=>{
        console.log(res)//B依赖的数据C依赖的数据
    })   
} catch(e){
    
}

应用场景2:中间件功能使用

描述:接口返回的数据量比较大,在一个then 里面处理 显得臃肿,多个渲染数据分别给个then,让其各司其职

//模拟后端返回的数据

let result = {
    bannerList:[
        {img:'轮播图地址'}
    //...
    ],
    storeList:[
        {name:'店铺列表'}
    //...
    ],
    categoryList:[
        {name:'分类列表'}
    //...
    ],
    //...
}

function getInfo(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve(result)
        },500)
    })
}

getInfo().then(res=>{

    let { bannerList } = res
    //渲染轮播图
    console.log(bannerList)
    return res
}).then(res=>{
    
    let { storeList } = res
    //渲染店铺列表
    console.log(storeList)
    return res
}).then(res=>{
    let { categoryList } = res
    console.log(categoryList)
    //渲染分类列表
    
    return res
})

推荐教程:《JS教程

The above is the detailed content of Some common application scenarios of front-end Promise. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete