当前位置:网站首页>Promise knowledge
Promise knowledge
2022-06-12 12:17:00 【Yolo. H】
Promise What is it? ?
- JS A new solution for asynchronous programming in
- promise Object is used to encapsulate an asynchronous operation and obtain its success / The result value of failure
Promise The state of (PromiseState) And change
state :
Instance object A property in
- pending Undecided
- resolved / fullfilled success
- rejected Failure
State change :
- pending Turn into resolved
- pending Turn into rejected
notes : Only here 2 Kind of , And one promise The object can only be changed once
Whether it becomes success or failure , There will be a result data
The result data of success is generally called value, The result data of failure is generally called reason
Promise The value of the object (PromiseResult)
Instance object Another property in
Save asynchronous tasks 『 success / Failure 』 Result
- resolve
- reject
Promise Workflow

API
1. Promise Constructors : Promise (excutor) {}
(1) executor function : actuator (resolve, reject) => {}
(2) resolve function : The function we call when the internal definition succeeds value => {}
(3) reject function : The function we call when the internal definition fails reason => {}
explain : executor Will be in Promise Inside Immediate synchronous call , Asynchronous operations are performed in the actuator
2. Promise.prototype.then Method : (onResolved, onRejected) => {}
(1) onResolved function : Successful callback function (value) => {}
(2) onRejected function : Failed callback function (reason) => {}
explain : Specified for success value The successful callback of and used to get the failure reason The failure callback of
Back to a new promise object
3. Promise.prototype.catch Method : (onRejected) => {}
(1) onRejected function : Failed callback function (reason) => {}
explain : then() The grammar sugar of , amount to : then(undefined, onRejected)
4. Promise.resolve Method : (value) => {}
(1) value: Successful data or promise object
- If the parameter passed in is Not Promise Object of type , The result returned is success promise object
- If the parameter passed in is Promise object , Then the result of the parameter determines resolve Result
explain : Return a success / The failure of the promise object
5. Promise.reject Method : (reason) => {}
(1) reason: The reason for the failure
explain : Return to a failed promise object
6. Promise.all Method : (promises) => {}
(1) promises: contain n individual promise Array of
explain : Back to a new promise, Only all of promise Success is the only way to succeed , If there is a direct failure
7. Promise.race Method : (promises) => {}
(1) promises: contain n individual promise Array of
explain : Back to a new promise, The first to finish promise The result state is the final result state
key problem :
How to change promise The state of ?
- resolve(value): Now it's pending It will become resolved
- reject(reason): Now it's pending It will become rejected
- Throw an exception : If it is currently pending It will become rejected
let p = new Promise((resolve, reject) => {
// 1. resolve function
resolve('ok'); // pending => fulfilled (resolved)
// 2. reject function
reject("error");// pending => rejected
// 3. Throw an error
throw ' Something is wrong. ';
});
One promise More than one success was specified / Failed callback function , Are they called ?
When promise It is called when it changes to the corresponding state
let p = new Promise((resolve, reject) => {
resolve('OK');
});
/// Specify callback - 1
p.then(value => {
console.log(value);
});
// Specify callback - 2
p.then(value => {
alert(value);
});
// Both of the above callback functions will call
change promise State and specify the callback function who comes first and then ?
- It's possible , Normally, the callback is specified first and then the state is changed , But you can also change the state before specifying the callback
- How to change state first and then specify callback ?
① Call directly in the actuator resolve()/reject()
② Call after a longer delay then() - When will the data be available ?
① 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
then() Back to the new promise What determines the outcome status of ?
- Simple expression : from then() The result of the specified callback function execution determines
- Detailed expression :
① 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 connect multiple operation tasks ?
(1) promise Of then() Back to a new promise, It can be done then() Chain call of
(2) adopt then Linked calls to connect multiple synchronizations / Asynchronous task
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('OK');
}, 1000);
});
p.then(value => {
return new Promise((resolve, reject) => {
resolve("success");
});
}).then(value => {
console.log(value);
}).then(value => {
console.log(value);
})
promise Abnormal transmission ?
(1) When using promise Of then Chain call , Failed callbacks can be specified at the end ,
(2) Exception in any previous operation , Will be sent to the last failed callback for processing
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('OK');
// reject('Err');
}, 1000);
});
p.then(value => {
// console.log(111);
throw ' Failed !';
}).then(value => {
console.log(222);
}).then(value => {
console.log(333);
}).catch(reason => {
console.warn(reason);
});
interrupt promise chain ?
(1) When using promise Of then Chain call , Interrupt in the middle , The subsequent callback function is no longer called
(2) There is only one way : Returns a pendding State of promise object
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('OK');
}, 1000);
});
p.then(value => {
console.log(111);
// There is and only one way
return new Promise(() => {
});
}).then(value => {
console.log(222);
}).then(value => {
console.log(333);
}).catch(reason => {
console.warn(reason);
});
Promise encapsulation Ajax Of GET request
/** * Encapsulate a function sendAJAX send out GET request * Parameters URL * Return results Promise object */
function sendAjax(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest;
xhr.responseType = 'json'
xhr.open('GET', url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// success
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
} else {
reject(xhr.status)
}
}
}
})
}
sendAjax('https://api.apiopen.top/getJoke').then(
value => {
console.log(value);
},
reason => {
console.log(reason);
}
)
Promise Encapsulate read file operation
1. Manually encapsulate functions
/** * Encapsulate a function mineReadFile Read file contents * Parameters : path File path * return : promise object */
function read(path) {
//Promise Parameters , The first is resolve, The second is reject
return new Promise((resolve, reject) => {
require('fs').readFile(path, (err, data) => {
if (err) reject(err)
resolve(data)
})
})
}
read('./content.txt')
.then(value => {
console.log(value.toString());
},
reason => {
console.log(reason);
}
)
2. Promisify
// introduce util modular
const util = require('util')
// introduce fs modular
const fs = require('fs')
// Returns a new function ,promisify Return to one promise object , No manual encapsulation
const read = util.promisify(fs.readFile)
read('./content.txt')
.then(value => {
console.log(value.toString());
},
reason => {
console.log(reason);
}
)
Custom encapsulation Promise
index.html
<!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>Document</title>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
<script src="./promise.js"></script>
</head>
<body>
<div class="container">
<h2 class="page-header">Promise encapsulation AJAX request </h2>
<button class="btn btn-primary"> Click Send </button>
</div>
<script> // let p = new Promise((resolve, reject) => {
// // Suppose you have an asynchronous situation // setTimeout(() => {
// // reject('error') // resolve('ok') // }, 1000) // }) // 1.then Callback function // const res = p.then(value => {
// console.log(value) // // return 'hello' // // return new Promise((resolve, reject) => {
// // resolve('happy new year') // // // reject('Error') // // }) // // throw 'FAIL' // }, reason => {
// console.warn(reason); // }) // console.log(res) // then Multiple callbacks // p.then(value => {
// alert(value); // }, reason => {
// alert(reason); // }) //2.catch Callback -- Specifies the callback function that failed // let res = p.catch(reason => {
// console.log(reason); // }) // console.log(res); // p.then(value => {
// console.log(111); // throw 'ERROR' // }).then(value => {
// console.log(222); // }).then(value => {
// console.log(333); // }).catch(reason => {
// console.log(reason); // }) // Value passed ,onResolved nothing // p.then().then(value => {
// console.log(222); // }).then(value => {
// console.log(333); // }).catch(reason => {
// console.log(reason); // }) // 3.Resolve Method The value passed in is successful , Status is successful ; What is passed in is a failed , It's also a failure // const p = Promise.resolve('OK') // const p2 = Promise.resolve(new Promise((resolve, reject) => {
// resolve('success') // })) // const p3 = Promise.resolve(Promise.resolve('oh yeah')) // console.log(p3); // 4.reject Method // const p = Promise.reject('Error') // const p2 = Promise.reject(new Promise((resolve, reject) => {
// resolve('OK') // })) // console.log(p) // console.log(p2) // 5.all Method // let p1 = new Promise((resolve, reject) => {
// resolve('OK') // }) // let p2 = Promise.resolve('Success') // let p3 = Promise.resolve('Oh yeah') // let result = Promise.all([p1, p2, p3]) // console.log(result); // 6. race Method // let p1 = new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve('OK') // }) // }) // let p2 = Promise.reject('Success') // let p3 = Promise.resolve('Oh yeah') // let result = Promise.race([p1, p2, p3]) // console.log(result); // 7.then Method Callback function , Asynchronous execution // let p1 = new Promise((resolve, reject) => {
// resolve('OK') // console.log(111); // }) // p1.then(value => {
// console.log(222); // }) // console.log(333); // class test // let p1 = new Promise((resolve, reject) => {
// setTimeout(() => {
// // resolve('OK') // // reject('Error') // }) // // resolve('OK') // // reject('Error') // // throw "Error" // }) // p1.then(value => {
// console.log(value); // }, reason => {
// console.log(reason); // }) // console.log(p1); console.log(Promise.resolve('OK')); </script>
</body>
</html>
Promise.js
class Promise {
constructor(executor) {
// Add attribute
this.PromiseState = 'pending'
this.PromiseResult = null
const self = this
// Single
// this.callback= {}
this.callbacks = []
// resolve function
function resolve(data) {
// there this Pointing to window
// console.log(this)
// The state of the setting object can only be changed once
if (self.PromiseState !== 'pending') return
//1. Modify object state
self.PromiseState = 'fulfilled'
//2. Set the object result value
self.PromiseResult = data
// Execution callback
// Single
// if (self.callback.onResolved) {
// self.callback.onResolved(data)
// }
// Multiple
setTimeout(() => {
self.callbacks.forEach(item => {
item.onResolved(data)
})
})
}
//reject function
function reject(data) {
// The state of the setting object can only be changed once
if (self.PromiseState !== 'pending') return
//1. Modify object state
self.PromiseState = 'rejected'
//2. Set the object result value
self.PromiseResult = data
// Multiple
setTimeout(() => {
self.callbacks.forEach(item => {
item.onRejected(data)
})
})
}
try {
// Call the executor function synchronously
executor(resolve, reject)
} catch (e) {
reject(e)
}
}
then(onResolved, onRejected) {
const self = this
// Determine the callback function parameters
if (typeof onRejected !== 'function') {
onRejected = reason => {
throw reason
}
}
if (typeof onResolved !== 'function') {
onResolved = value => value
// value => { return value }
}
//then Method returns a Promise object
return new Promise((resolve, reject) => {
function callback(type) {
try {
// Get the execution result of the callback function
let result = type(self.PromiseResult)
if (result instanceof Promise) {
//result yes Promise object
// Successful and failed callback functions
result.then(v => {
resolve(v)
}, r => {
reject(r)
})
} else {
// No Promise object
// take then Return the result of Promise Set status to success , The value is the execution result of the callback function
resolve(result)
}
} catch (e) {
reject(e)
}
}
// Call callback function
if (this.PromiseState === 'fulfilled') {
setTimeout(() => {
callback(onResolved)
})
}
if (this.PromiseState === 'rejected') {
setTimeout(() => {
callback(onRejected)
})
}
// Judge pending state
if (this.PromiseState === 'pending') {
this.callbacks.push({
onRejected: function () {
callback(onRejected)
},
onResolved: function () {
callback(onResolved)
}
})
}
})
}
catch(onRejected) {
return this.then(undefined, onRejected)
}
static resolve(value) {
return new Promise((resolve, reject) => {
if (value instanceof Promise) {
value.then(v => {
resolve(v)
}, r => {
reject(r)
})
} else {
resolve(value)
}
})
}
static reject(reason) {
return new Promise((resolve, reject) => {
reject(reason)
})
}
static all(promises) {
return new Promise((resolve, reject) => {
let cnt = 0
let arr = []
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
cnt++
// arr[i] = v
if (cnt === promises.length) {
resolve(arr)
}
}, r => {
reject(v)
})
}
})
}
static race(promises) {
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
resolve(v)
}, r => {
reject(r)
})
}
})
}
}
async function
<!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>Document</title>
</head>
<body>
<script> // async The function returns a value of Promise object // Promise The result of the object is determined by async The return value of the function execution determines async function main() {
// 1. You can return a non Promise Data of type // return 512 // 2. I can return one 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>
</body>
</html>
await expression : Only on the async in
<!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>Document</title>
</head>
<body>
<script> async function main() {
let p = new Promise((resolve, reject) => {
resolve('OK') // reject('Error') }) // 1. The right side is Promise object // When Promise Is a state of success , Returns the successful value // When Promise It's the state of failure , Throw an error try {
let result = await p console.log(result); } catch (e) {
console.log(e); } // 2. On the right are other types of data , Return the data // let result = await 20 // console.log(result); } main() </script>
</body>
</html>
async And await combination
send out AJAX request
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>async And await Combined transmission AJAX</title>
</head>
<body>
<button id="btn"> Click to get the paragraph </button>
<script> //axios function sendAJAX(url){
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open("GET", url); xhr.send(); // Processing results xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
// Judge success if(xhr.status >= 200 && xhr.status < 300){
// Successful results resolve(xhr.response); }else{
reject(xhr.status); } } } }); } // Segment sub interface address https://api.apiopen.top/getJoke let btn = document.querySelector('#btn'); btn.addEventListener('click',async function(){
// Get segment information let duanzi = await sendAJAX('https://api.apiopen.top/getJoke'); console.log(duanzi); }); </script>
</body>
</html>
边栏推荐
- For in and object The difference between keys()
- The direction of this
- The second day of QML study
- MVC mode, encryption, jsonwebtoken
- Win7 registers out of process components, services, and COM component debugging
- Miscellaneous instructions of arm instruction set
- Stress - system pressure simulation tool
- QT adds a summary of the problems encountered in the QObject class (you want to use signals and slots) and solves them in person. Error: undefined reference to `vtable for xxxxx (your class name)‘
- Point cloud registration -- GICP principle and its application in PCL
- TRON-api-波场转账查询接口-PHP版本-基于ThinkPHP5封装-附带接口文档-20220602版本-接口部署好适用于任何开发语言
猜你喜欢

QT adds a summary of the problems encountered in the QObject class (you want to use signals and slots) and solves them in person. Error: undefined reference to `vtable for xxxxx (your class name)‘

ARM processor mode and register

创建Servlet项目

点云配准--gicp原理与其在pcl中的使用

Problems encountered in installing canvas and errors encountered in running the project
![[foundation of deep learning] back propagation method (1)](/img/0b/540c1f94712a381cae4d30ed624778.png)
[foundation of deep learning] back propagation method (1)

LeetCode 497. Random points in non overlapping rectangles (prefix and + bisection)

你不会只会用console.log()吧?

Kdd2022 | edge information enhancement graph transformer

导航中,添加边框影响布局的解决方法
随机推荐
this的指向
Must do skill -- use ffmpeg command to quickly and accurately cut video
bind、call、apply三者的区别,还有bind()的封装
LeetCode 890. 查找和替换模式(模拟+双哈希表)
Why is there no traffic after the launch of new products? How should new products be released?
Linear model of machine learning
AGCO AI frontier promotion (6.12)
拿来就能用的网页动画特效,不来看看?
导航中,添加边框影响布局的解决方法
The difference between bind, call and apply, and the encapsulation of bind()
银行布局元宇宙:数字藏品、数字员工成主赛道!
获取本机所有ipv4, ipv6地址
LeetCode_字符串_简单_344.反转字符串
ARM processor mode and register
Dom+js+ carousel map + no time
The advantages of saving pointers when saving objects with vector and the use of reserve
用cloneNode 克隆,解决id问题/方法 深复制和浅复制修改id的方法
VGG小卷积代替大卷积 VS 深度可分离卷积
服务端渲染与客户端渲染的区别(优缺点)
B. Wall painting (C language)