当前位置:网站首页>ES6 promise learning notes
ES6 promise learning notes
2022-07-03 08:40:00 【Rain shallow listen to the wind sing】
List of articles
Basic introduction
Promise yes ES6 The introduction of a new solution to asynchronous programming . Grammatically Promise It's a constructor ,
Used to encapsulate asynchronous operations and obtain the results of their success or failure .
- Promise Constructors : Promise (excutor) {}
- Promise.prototype.then Method
- Promise.prototype.catch Method
resolve To be successful ,reject It's failure , These two are function Two formal parameters of , But are function
Call the failed function
promise Encapsulate and read files
Through the original reading, no promise
//1. introduce fs modular
const fs = require('fs');
//2. Call method to read file
fs.readFile('./resources/ For learning .md', (err, data)=>{
// If you fail , Throws an error
if(err) throw err;
// If there is no error , Then output the content
console.log(data);
console.log(data.toString());
});
here data yes buffer, Through the head tostring To string Use promise Method
//1. introduce fs modular
const fs = require('fs');
// //2. Call method to read file
// fs.readFile('./resources/ For learning .md', (err, data)=>{
// // If you fail , Throws an error
// if(err) throw err;
// // If there is no error , Then output the content
// console.log(data);
// console.log(data.toString());
// });
//3. Use Promise encapsulation
const p = new Promise(function(resolve, reject){
// Deliberate failure
//fs.readFile("./resources/ For learning .mda", (err, data)=>{
fs.readFile("./resources/ For learning .md", (err, data)=>{
// If judgment fails
if(err) reject(err);
// If it works
resolve(data);
});
});
p.then(function(value){
console.log(value.toString());
}, function(reason){
console.log(" Read failed !!");
});
When multiple tasks promise To have an advantage , Don't indent all the time
Promise encapsulation AJAX
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> send out AJAX request </title>
</head>
<body>
<script>
// Address of the interface : https://api.apiopen.top/getJoke
const p = new Promise((resolve, reject) => {
//1. Create objects
const xhr = new XMLHttpRequest();
//2. initialization
xhr.open("GET", "https://api.apiopen.top/getJ");
//3. send out
xhr.send();
//4. The binding event , Process response results
xhr.onreadystatechange = function () {
// Judge
if (xhr.readyState === 4) {
// Determine the response status code 200-299
if (xhr.status >= 200 && xhr.status < 300) {
// It means success
resolve(xhr.response);
} else {
// If you fail
reject(xhr.status);
}
}
}
})
// Specify callback
p.then(function(value){
console.log(value);
}, function(reason){
console.error(reason);
});
</script>
</body>
</html>
Promise Of then Method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise.prototype.then</title>
</head>
<body>
<script>
// establish promise object
const p = new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve(' User data ');
// reject(' Error ');
}, 1000)
});
// call then Method then The return result of the method is Promise object , The object state is determined by the execution result of the callback function
//1. If the result returned in the callback function is Not promise Properties of type , Status is success , The return value is the successful value of the object
// const result = p.then(value => {
// console.log(value);
// //1. Not promise Properties of type
// // return 'iloveyou';
// //2. yes promise object
// // return new Promise((resolve, reject)=>{
// // // resolve('ok');
// // reject('error');
// // });
// //3. Throw an error
// // throw new Error(' Error !');
// throw ' Error !';
// }, reason=>{
// console.warn(reason);
// });
// call chaining
p.then(value=>{
}).then(value=>{
});
</script>
</body>
</html>
Multiple content reads
// introduce fs modular
const fs = require("fs");
// fs.readFile('./resources/ For learning .md', (err, data1)=>{
// fs.readFile('./resources/ Rice transplanting Poetry .md', (err, data2)=>{
// fs.readFile('./resources/ I have a feeling of reading .md', (err, data3)=>{
// let result = data1 + '\r\n' +data2 +'\r\n'+ data3;
// console.log(result);
// });
// });
// });
// Use promise Realization
const p = new Promise((resolve, reject) => {
fs.readFile("./resources/ For learning .md", (err, data) => {
resolve(data);
});
});
p.then(value => {
return new Promise((resolve, reject) => {
fs.readFile("./resources/ Rice transplanting Poetry .md", (err, data) => {
resolve([value, data]);
});
});
}).then(value => {
return new Promise((resolve, reject) => {
fs.readFile("./resources/ I have a feeling of reading .md", (err, data) => {
// Push the
// value.push(data);
// resolve(value);
resolve([value, data]);
});
})
}).then(value => {
console.log(value.join('\r\n'));
});
Promise catch
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>catch Method </title>
</head>
<body>
<script>
const p = new Promise((resolve, reject)=>{
setTimeout(()=>{
// Set up p The state of the object is failed , And set the failed value
reject(" Error !");
}, 1000)
});
// p.then(function(value){}, function(reason){
// console.error(reason);
// });
p.catch(function(reason){
console.warn(reason);
});
</script>
</body>
</html>
边栏推荐
- 数据库原理期末复习
- 了解小程序的笔记 2022/7/3
- Encoding and decoding of golang URL
- [MySQL] MySQL Performance Optimization Practice: introduction of database lock and index search principle
- 二进制转十进制,十进制转二进制
- Collection interface
- [rust notes] 05 error handling
- UE4 source code reading_ Bone model and animation system_ Animation process
- Base64 and base64url
- Swagger document configuration
猜你喜欢
单调栈-42. 接雨水
Chocolate installation
Gradle's method of dynamically modifying APK package name
[rust notes] 02 ownership
Installation of PHP FPM software +openresty cache construction
Mxone Pro adaptive 2.0 film and television template watermelon video theme apple cmsv10 template
Clion toolchains are not configured configure disable profile problem solving
Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)
Student educational administration management system of C # curriculum design
Notes on understanding applets 2022/7/3
随机推荐
Huawei interview summary during the epidemic
Base64 and base64url
Servlet的生命周期
Development experience and experience
Osganimation library parsing
UE4 plug in development
[concurrent programming] concurrent tool class of thread
注解简化配置与启动时加载
【Rust笔记】06-包和模块
MySQL containerization (1) docker installation MySQL
Collection interface
Unity Editor Extension - Outline
Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
[concurrent programming] consistency hash
Jupyter remote server configuration and server startup
Gradle's method of dynamically modifying APK package name
单调栈-503. 下一个更大元素 II
Mxone Pro adaptive 2.0 film and television template watermelon video theme apple cmsv10 template
如何应对数仓资源不足导致的核心任务延迟
producer consumer problem