当前位置:网站首页>Promise details
Promise details
2022-07-27 07:57:00 【ik i5】
1. What is? Promise Well ?
Promise Is a solution to asynchronous programming
When will we deal with asynchronous events ?
- A very common scenario is network request .
- We encapsulate a network request function , Because you can't get the results right away , So it can't be as simple as 3+4=7 Return the result as well .
- So often we pass in another function , When the data request is successful , Call back the data through the incoming function .
- If it's just a simple network request , Then this kind of plan will not bring us much trouble .
- however , When network requests are very complex , Will appear Back to hell ( Callback inside and callback ).
1. 1 Callback of network request
Let's consider the following scenario ( There is an element of exaggeration ):
- We need to go through a url1 Load a data from the server data1,data1 Contains the next request for url2
- We need to pass data1 Take out url2, Load data from server data2,data2 Contains the next request for url3
- We need to pass data2 Take out url3, Load data from server data3,data3 Contains the next request for url4
- Send network request url4, Get the final data data4

The above code looks ok , But such code is neither elegant nor difficult to maintain , So we can use Promise To solve such problems gracefully .
2. Promise Basic use of
2. 1. Asynchronous events for timers
- Let's take a look first Promise The most basic grammar .
- here , We use a timer to simulate asynchronous events :
- Suppose the following data It's from the Internet 1 Data requested in seconds
- console.log It's how we deal with it .

This is how we used to deal with it , We'll replace it with Promise Code

- This example will make us feel like taking off our pants and farting , carry coals to newcastle
First , Below Promise The code is obviously more complex than the code above .
secondly , Below Promise The resolve、reject、then、catch What are all these things ?
Let's ignore the first complexity issue , Because such a big fart program can not see Promise The real effect .
2. 2. Timer asynchronous event resolution
Let's take a real look at what this program does ?
- new Promise It's obvious to create a Promise object
- In parentheses ((resolve, reject) => {}) And it's obviously a function , And here we use the arrow function we just learned before .、
however resolve, reject What are they ?
Let's first know a fact : Creating Promise when , The arrow function passed in is fixed ( We usually write like this )
resolve and reject Both of them are also functions , Usually , We will decide which one to call according to the success and failure of the requested data .
Success or failure ?
- If it's successful , So usually we call resolve(messsage), This is the time , Our follow-up then Will be recalled .
- If it's a failure , So usually we call reject(error), This is the time , Our follow-up catch Will be recalled .
OK, This is it. Promise The most basic use of .
// Sync
const name = 'yyy';
console.log(name);
const result = 3 + 5;
// asynchronous
// 1. Use setTimeout Use a timer to simulate asynchronous events
// setTimeout(() => {
// console.log('Hello World');
// }, 1000)
// When will it be used Promise?
// In general, when there is asynchronous operation , Use Promise For this * Asynchronous operation for encapsulation *
// new -> Constructors (1. Saved some status information 2. Execute the passed in function )
// When executing the incoming callback function , Two parameters will be passed in , resolve solve , reject Refuse . These two are themselves functions
// Parameters -> function ((resolve, reject)
// Any asynchronous operation in the future can be encapsulated in Promise Inside
new Promise((resolve, reject) => {
setTimeout(() => {
// If there is code to be processed, it will not be directly put here stay then Inside processing data
// console.log('hello world');
// console.log('hello world');
// console.log('hello world');
// console.log('hello world');
// If you succeed, go to then Where?
// resolve('Hello World')
// Call... When it fails reject Will go to catch Where?
reject('error message')
}, 1000)
}).then((data) => {
// then There is also a function
// 1.100 Line processing code
console.log(data);
console.log(data);
console.log(data);
console.log(data);
console.log(data);
}).catch((err) => {
console.log(err);
})
// Through the... In the callback resolve(data) Put this promise Marked as resolverd,
// Then go on to the next step then((data)=>{//do something}),resolve The parameter in is what you want to pass in then The data of .
2. 3 Promise Three states and other processing forms
Three states of asynchronous operation :
- pending: Wait state , For example, a network request is in progress , Or the timer doesn't run out of time .- fulfill: State of satisfaction , When we take the initiative to call back resolve when , In that state , And it will call back .then()- reject: Rejection status , When we take the initiative to call back reject when , In that state , And it will call back .catch()
- Promise Another processing form of
new Promise((resolve, reject) => {
setTimeout(() => {
// resolve('Hello Vuejs')
reject('error message')
}, 1000)
// Don't want to write at the same time then and catch Words then Two functions can be directly passed in data,err
}).then(data => {
console.log(data);
}, err => {
console.log(err);
})
3 . Promise Chain call of
3. 1 Promise call chaining
- We looked at Promise Flow chart for , Find out whether it's then still catch Can return a Promise object .
- therefore , Our code can actually make chain calls :
// Parameters -> function (resolve, reject)
// resolve, reject In itself, they are functions
// Chain programming
new Promise((resolve, reject) => {
// The code of the first network request
setTimeout(() => {
resolve()
}, 1000)
}).then(() => {
// The processing code to get the result for the first time
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
// If there is a callback, you can write it here At the first .then() Continue behind .then()
return new Promise((resolve, reject) => {
// The code of the second network request
setTimeout(() => {
resolve()
}, 1000)
})
}).then(() => {
// The second processing code
console.log('Hello Vuejs');
console.log('Hello Vuejs');
console.log('Hello Vuejs');
console.log('Hello Vuejs');
console.log('Hello Vuejs');
console.log('Hello Vuejs');
return new Promise((resolve, reject) => {
// The code of the third network request
setTimeout(() => {
resolve()
})
})
}).then(() => {
// The third processing code
console.log('Hello Python');
console.log('Hello Python');
console.log('Hello Python');
console.log('Hello Python');
console.log('Hello Python');
})
3. 2 Promise Short for chain call
Task requirements such as :
- Network request : aaa -> Do it yourself (10 That's ok )
- After processing splicing : aaa111 -> Do it yourself (10 That's ok )
- After processing splicing : aaa111222 -> Do it yourself
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('aaa')
}, 1000)
}).then(res => {
// 1. Do it yourself 10 Line code
console.log(res, ' First floor 10 Line processing code ');
// 2. The results are processed for the first time
return new Promise((resolve, reject) => {
// resolve(res + '111')
reject('err')
})
}).then(res => {
console.log(res, ' Second floor 10 Line processing code ');
return new Promise(resolve => {
resolve(res + '222')
})
}).then(res => {
console.log(res, ' On the third floor 10 Line processing code ');
}).catch(err => {
console.log(err);
})
First extraction new Promise(resolve => resolve( result )) Abbreviation
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('aaa')
}, 1000)
}).then(res => {
// 1. Do it yourself 10 Line code
console.log(res, ' First floor 10 Line processing code ');
// 2. The results are processed for the first time
return Promise.resolve(res + '111')
}).then(res => {
console.log(res, ' Second floor 10 Line processing code ');
return Promise.resolve(res + '222')
}).then(res => {
console.log(res, ' On the third floor 10 Line processing code ');
})

Pull away for the second time : Omit Promise.resolve
/* ----- Omit Promise.resolve, direct return res ----- */
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('aaa')
}, 1000)
}).then(res => {
// 1. Do it yourself 10 Line code
console.log(res, ' First floor 10 Line processing code ');
// 2. The results are processed for the first time
return res + '111'
}).then(res => {
console.log(res, ' Second floor 10 Line processing code ');
return res + '222'
}).then(res => {
console.log(res, ' On the third floor 10 Line processing code ');
})

3. 3 throw Throw an exception manually
The above is the success of each layer , How to write the failure ?
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('aaa')
}, 1000)
}).then(res => {
// 1. Do it yourself 10 Line code
console.log(res, ' First floor 10 Line processing code ');
// 2. The results are processed for the first time
// return Promise.reject('error message')
// throw Throw an exception manually
throw 'error message' // Print error message
}).then(res => {
console.log(res, ' Second floor 10 Line processing code ');
return Promise.resolve(res + '222')
}).then(res => {
console.log(res, ' On the third floor 10 Line processing code ');
}).catch(err => {
console.log(err);
})
3. 4 Promise Of all Methods use
- The requirement itself depends on two requests I'm not sure which one asked to come back first , So we have to deal with both handleResult
- Ensure that the data is successful in both network requests To get the data
// The requirement itself depends on two requests I'm not sure which one asked to come back first , So we have to deal with both handleResult
// Request a :
// let isResult1 = false
// let isResult2 = false
// $ajax({
// url: '',
// success: function () {
// console.log(' result 1');
// isResult1 = true
// handleResult()
// }
// })
// // Request 2 :
// $ajax({
// url: '',
// success: function () {
// console.log(' result 2');
// isResult2 = true
// handleResult()
// }
// })
//
// function handleResult() {
// if (isResult1 && isResult2) {
// //
// }
// }
// Promise.all Multiple Promise The example is packaged into a new Promise example . Unified callback
// meanwhile , Success and failure return values are different , Success returns an array of results , And when they fail, they return to be the first reject Value of failure state .
Promise.all([
// new Promise((resolve, reject) => {
// $.ajax({
// url: 'url1',
// success: function (data) {
// resolve(data)
// }
// })
// }),
// new Promise((resolve, reject) => {
// $.ajax({
// url: 'url2',
// success: function (data) {
// resolve(data)
// }
// })
// })
new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
name: 'yyy',
age: 18
})
}, 2000)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
name: 'kobe',
age: 19
})
}, 1000)
})
]).then(results => {
console.log(results);
})

边栏推荐
- Grandson's questions are difficult, and his son's invigilation is strict. I can't do it. Pay back my school money
- [QT] unable to open the containing file pcap.h (C1083) in QT creator
- 将对象转换为键值对
- MCU multi-level menu
- 这次龙蜥展区玩的新花样,看看是谁的 DNA 动了?
- 服务器网络测试的方法
- [resolved] the new version of pychart (2022) connects to the server to upload files and reports an error of "command Rsync is not found in path", and the files cannot be synchronized
- [ten thousand words long article] thoroughly understand load balancing, and have a technical interview with Alibaba Daniel
- What is a rebound shell? What's the use of bouncing shells?
- C语言:随机生成数+插入排序
猜你喜欢

Promise详解

Zero training platform course-1. SQL injection Foundation

Do me a favor ~ don't pay attention, don't log in, a questionnaire in less than a minute
![[ten thousand words long article] thoroughly understand load balancing, and have a technical interview with Alibaba Daniel](/img/fc/1ee8b77d675e34da2eb8574592c489.png)
[ten thousand words long article] thoroughly understand load balancing, and have a technical interview with Alibaba Daniel

Installation and use of apifox
![API version control [eolink translation]](/img/3a/8a78e57a2474f33d011d91631fde74.jpg)
API version control [eolink translation]

OpenGL shader learning notes: varying variables

C#winform 窗体事件和委托结合用法

LeetCode56. 合并区间

What about idea Chinese garbled code
随机推荐
什么是真正的HTAP?(一)背景篇
Chromedriver download - self use
二零二零年终总结
剑指 Offer 58 - I. 翻转单词顺序
【Golang】golang开发微信公众号网页授权功能
Lua stateful iterator
软件调优方法有哪些?看看飞腾技术专家怎么说 | 龙蜥技术
C commissioned use cases
Resttemplate connection pool configuration
C语言:优化后的希尔排序
SQL labs SQL injection platform - level 1 less-1 get - error based - Single Quotes - string (get single quote character injection based on errors)
帮个忙呗~不关注不登录,不到一分钟的一个问卷
2020国际机器翻译大赛:火山翻译力夺五项冠军
Happy holidays, everyone
Leetcode54. 螺旋矩阵
Primary key in MySQL secondary index - MySQL has a large number of same data paging query optimization
kalibr标定realsenseD435i --多相机标定
Practical new drug R & D project management platform
[resolved] the new version of pychart (2022) connects to the server to upload files and reports an error of "command Rsync is not found in path", and the files cannot be synchronized
抽象工厂模式