当前位置:网站首页>[promise I] introduction of promise and key issues of hand rolling
[promise I] introduction of promise and key issues of hand rolling
2022-06-27 03:24:00 【Yiyao Bingo】
Winter vacation to see the present promise, In preparation for the interview , Must give an end , It's really hard to make a nest with your hands
List of articles
- One 、 Promise Introduction and basic use
- Two 、Promise encapsulation
- 3、 ... and 、 Promise Introduction to object properties , Workflow ...
- Four 、Promise key problem
- 4-1 How to modify promise object The state of
- 4-2 One promise More than one success was specified / Failed callback function 【then Method 】, Whether multiple callbacks can be executed ?
- 4-3 change promise Status and specified callback function The question of order
- 4-4 then What determines the result returned by the method
- 4-5 Cascade multiple operation tasks
- 4-6 extraordinary transmission
- 4-7 interrupt Promise chain
- 5、 ... and 、 Custom handwriting Promise
- 6、 ... and 、 async and await
A certain node.js The basis of
One 、 Promise Introduction and basic use
1-1 Introduce
Concept
- Promise It's a new technology
- Promise yes JS A new solution for asynchronous programming in
- remarks : Before that, we simply used callback functions
Specifically :
- Grammatically : Promise It's a constructor
- function : promise Object is used to encapsulate an asynchronous operation and obtain its success / The value of failure
Asynchronous programming
fs File operations
require('fs').readFile('./index/html',(err,data) => { })Database operation
AJAX
$.get('/server',(data) => { })Timer
setTimeout(() => { }, 2000);
1-2 Why want to use Promise
- Specifying callback functions is more flexible
- old : You must specify... Before starting an asynchronous task
- promise : Start asynchronous task => return promise object => to promise Object binding callback function ( You can even specify... At the end of an asynchronous task / Multiple )
- Support chain calls , It can solve the problem of callback to hell
- Callback function nested call , The result of asynchronous execution of external callback function is the condition of nested callback execution
- The characteristics of callback hell :
- Not easy to read
- Not convenient for exception handling
1-3 Promise First experience
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise Request lottery interface </title>
</head>
<body>
<div class="container">
<div class="page-header">Promise First experience </div>
<button class="btn btn-primary" id="btn"> Click on the draw </button>
</div>
<script>
// Generate random number
function rand(m, n) {
return Math.ceil(Math.random() * (n - m + 1) + m - 1);
}
/* Click button , 2 s Whether to win the prize will be displayed after ( 30 % Probability winning ) If you win, pop up Congratulations If you don't win, pop up Make persistent efforts */
// Get element object
const btn = document.querySelector('#btn');
// Bind click event
btn.addEventListener('click', function() {
// setTimeout(() => {
// // 30%, 1-100 1 2 30
// // Get from 1-100 A random number of
// let n = rand(1, 100);
// // Judge
// if (n <= 30) {
// alert(' Congratulations ');
// } else {
// alert("zaijiezailin");
// }
// }, 1000)
const p = new Promise((resolve, reject) => {
setTimeout(() => {
// 30%, 1-100 1 2 30
// Get from 1-100 A random number of
let n = rand(1, 100);
// Judge
if (n <= 30) {
resolve(); // take promise The turntable of the object is set to success
} else {
reject(); // take promise The state of the object is set to failed
}
}, 1000)
});
// call then Method
p.then(() => {
alert(' Congratulations , The prize is 10 ten thousand ');
}, () => {
alert(' Make persistent efforts ');
})
})
// Promise Formal realization
// resolve solve Data of function type
// reject Refuse Data of function type
</script>
</body>
</html>
1-4 fs Read the file
1-5 Ajax request
Two 、Promise encapsulation
2-1 Promise encapsulation fs modular
/* Encapsulate a function mineReadFile Read the file Parameters : path File path return : promise object */
function mineReadFile(path) {
return new Promise((resolve, reject) => {
// Read the file
require('fs').readFile(path, (err, data) => {
// Judge
if (err) reject(err);
// success
resolve(data);
})
})
}
mineReadFile('./content.txt')
.then(value => {
// Output file content
console.log(value.toString());
}, reason => {
console.log(reason);
})
2-2 util.promisify(original)【 Did not understand 】
- original
<Function>
- original
Pass in a callback style function that follows common priority errors ( That is to (err,value) => … Callback as the last parameter ), And return a return promise Version of
2-3 encapsulation Ajax request
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise encapsulation Ajax request </title>
</head>
<body>
<!-- Encapsulate a function sendAJAX send out GET AJAX request
Parameters URL
Return results Promise object -->
<script>
function sendAJAX(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send();
// Processing results
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(error);
}
}
}
})
}
sendAJAX('https://netease-cloud-music-api-crete722p-hannah-bingo.vercel.app/user/detail?uid=32953014')
.then(value => {
console.log(value);
}, reason => {
console.log(reason);
})
</script>
</body>
</html>
3、 ... and 、 Promise Introduction to object properties , Workflow …

3-1 Promise The state of 【PromiseState】
promise The state of change
pending Turn into resolved ( The successful outcome data is called value)
pending Turn into rejected ( The failed result data is called reason)
promise The state of : It refers to a property in the instance object
[PromiseState]- pending Undecided
- resolved / fullfilled success
- rejected Failure
3-2 Promise object Of value 【PromiseResult】
- Another property in the instance object 【PromiseResult】
- Save the object [ success / Results of failure ]
- reject
- resolve
3-3 Promise workflow

3-4 Promise Of API
3-4-1 Constructors -then-catch
Promise Constructors
Promise(excutor){}- executor function : actuator (resolve, reject) => {}
- resolve function : The function we call when the internal definition succeeds value => {}
- reject function : Internal definition failed when The function we call resaon => {}
explain : executor Will be in Promise Internal immediate synchronization call , Asynchronous operations are performed in the actuator
<script> let p = new Promise((resolve, reject) => { // Synchronously called console.log(111); }) console.log(22); </script> // result : 111 22Promise.prototype.thenMethod : (onResolved, onRejected)=> {}- onResolved function : Successful callback function (value) => {}
- onRejected function : Failed callback function (reason) => {}
Specified for success value Successful callback and Used to get failed reason The failure callback of , Back to a new promise object
Promise.prototype.catch Method :(onRejected) => {}
onRejected function : Failed callback function (reason) => {}
<script> let p = new Promise((resolve, reject) => { reject('error'); }) p.catch(reason => { console.log(reason); }) </script>
3-4-2 Function object , Non instance object :resolve,reject,all,race Method
Promise.resolve Method : (value) => {}
value : Successful data or promise object
Return a success / The failure of the promise object
<script> let p1 = Promise.resolve(521); // If the parameter passed in is not Promise Object of type , The result returned is success promise object // If the passed parameter is Promise object , Then the result of the parameter determines resolve Result let p2 = Promise.resolve(new Promise((resolve, reject) => { resolve('ok'); })) console.log(p1); console.log(p2); </script>
Promise.reject Method : (reason)=> {} 【 Quickly return failed promise object 】
reason : The reason for the failure
Return to a failed promise object
<script> let p = Promise.reject(521); console.log(p); </script>
Promise.all Method : (promises) => {}
- promises : contain n individual promises Array of
- Back to a new promise, Only all of promise Success is the only way to succeed , As long as there is one failure, it will fail directly
<script> let p1 = new Promise((resolve, reject) => { resolve('OK'); }) let p2 = Promise.reject('EEE'); let p3 = Promise.resolve('Oh Yeah'); const result = Promise.all([p1, p2, p3]); const reject = Promise.all([p1, p3]) console.log(result); console.log(reject); </script>Promise.race Method : (promises)=> {}
- promises : contain n and promise Array of
- Back to a new promise, The first to finish promise The result state is the final result state
Four 、Promise key problem
4-1 How to modify promise object The state of
resolve(value) : If it is currently pending Will become resolved
reject(reason) : If it is currently pending Will become rejected
Throw an exception : If it is currently pending Will become rejected
<script> let p = new Promise((resolve, reject) => { // 1. By calling resolve function // resolve('ok'); // pending => fulfilled(resolved) // 2. reject function // reject("error"); // pending => rejected // 3. Throw an error throw " have a problem " }); console.log(p); </script>
4-2 One promise More than one success was specified / Failed callback function 【then Method 】, Whether multiple callbacks can be executed ?
- When Promise When changing to the corresponding state , Will be called
<script>
let p = new Promise((resolve, reject) => {
// Change state
resolve('OK');
})
// Specify callback -1
p.then(value => {
console.log(value);
})
// Specify callback -2
p.then(value => {
alert(value);
})
</script>
4-3 change promise Status and specified callback function The question of order
It's possible , Normally First specify the callback function Then change the State , But you can also change the state first At the specified callback
How to change the state first in the specified callback
Call directly in the actuator resolve(), reject()
Delay Take longer to call then()
<script> let p = new Promise((resolve, reject) => { // resolve("ok"); // Asynchronous task , Callback executed first setTimeout(() => { resolve('OK'); }, 1000) }) p.then(value => { console.log(value); }, reason => { }) </script>
When to get the data
- If the callback is specified first , When the state changes , The callback function will call , Get data
- If you change the state first , When a callback is specified , The callback function will call , Get data
4-4 then What determines the result returned by the method
- from then() The result of the specified callback function execution determines
- If an exception is thrown , new promise Turn into rejected,reason Exception thrown for
- If yes or no is returned promise Any value of , new promise Turn into resolved,value For the returned value
- If you return another new promise, this promise The result will be new promise Result
- promise How to concatenate multiple operation tasks
- promise Of then() Back to a new promise, You can develop then() Chain call of
- adopt then Chain call of Connect multiple synchronizations in series / Asynchronous task
4-5 Cascade multiple operation tasks
- promise Of then() Back to a new promise, You can develop then() Chain call of
- adopt then Of Chained calls concatenate multiple synchronizations / Asynchronous task
4-6 extraordinary transmission
- Concept :
- When using promise Of then Chain call , Failed callbacks can be specified at the end
- Exception in any previous operation , Will be sent to the last failed callback for processing
- interrupt promise chain
- When using promise Of then Chain call , Interrupt in the middle , Not calling the callback function after
- Method : Returns a pendding State of promise object
4-7 interrupt Promise chain
return new Promise(() => { });
5、 ... and 、 Custom handwriting Promise
Hand rolling promise Source code , Please refer to :
6、 ... and 、 async and await
6-1 async function
The return value of the function is promise object
promise The result of the object is determined by async The return value of the heart of the function determines
<script> async function main() { // If the return value is a non promise Data of type return 521; // If you return a Promise object return new Promise((resolve, reject) => { resolve('OK'); // reject('Error') }) // 3. Throw an exception throw "oh no"; } let result = main(); console.log(result); </script>
6-2 await expression
- await The expression on the right is usually promise object , But it can also be other values
- If the expression is promise object ,await The return is promise The value of success
- If the expression is another value , Take this value directly as await The return value of
6-3 Be careful
- await Must be written in async Function , but async There can be no await
- without await Of promise failed , Will throw an exception , Need to pass through try …catch Capture processing
边栏推荐
- 人群模拟
- resnet152 辣椒病虫害图像识别1.0
- 正则表达式:语法
- Pat grade a 1020 tree Traversals
- 测试nohup和&的各自作用
- ORM cache package for laravel
- Sword finger offer 𞓜: stack and queue (simple)
- Cs5213 HDMI to VGA (with audio) single turn scheme, cs5213 HDMI to VGA (with audio) IC
- mmdetection ValueError: need at least one array to concatenate解决方案
- 2021:Greedy Gradient Ensemble for Robust Visual Question Answering
猜你喜欢

Is the division of each capability domain of Dama, dcmm and other data management frameworks reasonable? Is there internal logic?

jmeter分布式压测

Pat grade a 1019 general palindromic number

PAT甲级 1018 Public Bike Management

Solve the problem of error reporting in cherry pick submission

Cvpr2021:separating skills and concepts for new visual question answering

超級詳細,2 萬字詳解,吃透 ES!

Qingscan use

Mmdetection valueerror: need at least one array to concatenate solution

PAT甲级 1019 General Palindromic Number
随机推荐
2021:Zero-shot Visual Question Answering using Knowledge Graphs使用知识图的零次视觉问答
Flink學習2:應用場景
2022中式面点师(高级)复训题库及在线模拟考试
苹果唯一图谱架构常识
平均风向风速计算(单位矢量法)
PAT甲级 1018 Public Bike Management
Solve the problem of error reporting in cherry pick submission
2016Analyzing the Behavior of Visual Question Answering Models
Flink learning 2: application scenarios
ESP8266
PAT甲级 1023 Have Fun with Numbers
再探Handler(下)(Handler核心原理最全解析)
ORM cache package for laravel
Introduction to stm32
Topolvm: kubernetes local persistence scheme based on LVM, capacity aware, dynamically create PV, and easily use local disk
mmdetection ValueError: need at least one array to concatenate解决方案
Calculation of average wind direction and speed (unit vector method)
1. Project preparation and creation
对数器
How to solve the problem of low applet utilization