Some common application scenarios of front-end Promise
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] })
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 })
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 togetherThinking: 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 writein 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 outfunction 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) })Copy after login
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)//网络不佳 })Copy after login
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

Vue is a popular front-end framework, and you often encounter various errors and problems when developing applications. Among them, Uncaught(inpromise)TypeError is a common error type. In this article, we will discuss its causes and solutions. What is Uncaught(inpromise)TypeError? Uncaught(inpromise)TypeError error usually appears in

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Use Promise objects to change ordinary functions to return Promise to solve the problem of callback hell. Understand the success and failure calling logic of Promise and make adjustments flexibly. Understand the core knowledge, use it first, and slowly integrate and absorb the knowledge.

The promise object states are: 1. pending: initial state, neither success nor failure state; 2. fulfilled: means the operation was successfully completed; 3. rejected: means the operation failed. Once a Promise object is completed, it will change from the pending state to the fulfilled or rejected state, and cannot change again. Promise objects are widely used in JavaScript to handle asynchronous operations such as AJAX requests and timed operations.

Browser compatibility: Which browsers support Promises? As the complexity of web applications continues to increase, developers are eager to solve the problem of asynchronous programming in JavaScript. In the past, developers often used callback functions to handle asynchronous operations, but this resulted in code that was complex and difficult to maintain. To solve this problem, ECMAScript6 introduced Promise, which provides a more intuitive and flexible way to handle asynchronous operations. Promise is a method used to handle exceptions

Advantages: asynchronous and non-blocking, does not block the main thread; improves code readability and maintainability; built-in error handling mechanism.

In front-end js learning, the most uncomfortable thing for everyone is the problem of asynchronousness. To solve problems such as asynchronous and callback hell, you must learn promises. For most front-end programmers, promises are simply a nightmare. This article starts from the easy-to-understand Angle is used as the entry point to help everyone easily master promises.
