当前位置:网站首页>Basic functions of promise [IV. promise source code]
Basic functions of promise [IV. promise source code]
2022-06-27 03:25:00 【Yiyao Bingo】
For hand rolling promise Bedding made
Supporting notes view :promise Introduction and key problems of hand rolling
List of articles
- One 、 Promise Functional experience
- 1-1 Promise Request lottery interface .html
- 1-2 fs Read the file .js
- 1-3 Ajax request .html
- 1-4 promise Encapsulate contact -fs modular
- 1-5 promise encapsulation AJAX request .html
- 1-6 Promise Constructor for catch
- 1-7 Promise API - resolve.html
- 1-8 Promise API - reject.html
- 1-9 Promise.all Method .html
- 1-10 Promise.race Method .html
- Two 、 promise key problem
- 2-1 1- State modification .html
- 2-2 2- Whether multiple callbacks can be executed .html
- 2-3 3-then Execute first or change the state to execute first .html
- 2-4 4-then What is the decision of the result returned by the method .html
- 2-5 5- Cascade multiple operation tasks .html
- 2-6 6- extraordinary transmission x The phenomenon .html
- 2-7 7- interrupt Promise chain .html
One 、 Promise Functional experience
1-1 Promise Request lottery interface .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>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(n); // take promise The turntable of the object is set to success } else {
reject(n); // take promise The state of the object is set to failed } }, 1000) }); console.log(p); // call then Method p.then((value) => {
alert(' Congratulations , The prize is 10 ten thousand ' + value); }, (reason) => {
alert(' Make persistent efforts ' + reason); }) }) // Promise Formal realization // resolve solve Data of function type // reject Refuse Data of function type </script>
</body>
</html>
1-2 fs Read the file .js
Create according to the corresponding path content.txt
const fs = require('fs');
// Callback function form
// fs.readFile('./content.txt', (err, data) => {
// // If something goes wrong , Throws an error
// if (err) throw err;
// // Output file content
// console.log(data.toString());
// })
//Promise form
let p = new Promise((resolve, reject) => {
fs.readFile('./content.txt', (err, data) => {
// If something goes wrong , Throws an error
if (err) reject(err);
// Output file content
resolve(data);
})
})
p.then((value) => {
console.log(value.toString());
}, reason => {
console.log(reason);
})
1-3 Ajax request .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>Promise encapsulation Ajax request </title>
</head>
<body>
<div class="container">
<h2 class="page-header">Promise encapsulation AJAX operation </h2>
<button class="btn btn-primary" id="btn"> Click Send AJAX</button>
</div>
<script> const btn = document.querySelector('#btn'); btn.addEventListener('click', function() {
const p = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://netease-cloud-music-api-crete722p-hannah-bingo.vercel.app/user/detail?uid=32953014'); xhr.send(); xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response); } else {
reject(xhr.status); } } } }) p.then(value => {
console.log(value); }, reason => {
console.warn(reason); }) }) </script>
</body>
</html>

1-4 promise Encapsulate contact -fs modular
/* Encapsulate a function mineReadFile Read the file Parameters : path File path return : promise object */
const {
readFile } = require('fs');
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);
})

1-5 promise encapsulation AJAX request .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>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) => {
// Create an asynchronous call object const xhr = new XMLHttpRequest(); // Specify the HTTP Requested method ,URL And verification information xhr.open("GET", url); // send out HTTP request xhr.send(); // Processing results // Set response HTTP Functions that request state changes 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>
1-6 Promise Constructor for catch
<!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 API</title>
</head>
<body>
<script> let p = new Promise((resolve, reject) => {
// Synchronously called // console.log(111); // modify promise Object state reject('uu'); }) console.log(p); // perform catch Method p.catch(reason => {
console.log(reason); }) </script>
</body>
</html>

1-7 Promise API - resolve.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>Promise API - resolve</title>
</head>
<body>
<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'); reject('err'); })) console.log(p1); console.log(p2); p2.catch(reason => {
console.log(reason); }) </script>
</body>
</html>

1-8 Promise API - reject.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>Promise API - reject</title>
</head>
<body>
<script> let p = Promise.reject(521); console.log(p); let p3 = Promise.reject(new Promise((resolve, reject) => {
resolve("ok"); })) // The status is failure , The result returned is success console.log(p3); </script>
</body>
</html>

1-9 Promise.all Method .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>Promise API - all</title>
</head>
<body>
<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>
</body>
</html>

1-10 Promise.race Method .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>Promise.race Method </title>
</head>
<body>
<script> let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('OK'); }, 1000) }) let p2 = Promise.reject('EEE'); let p3 = Promise.resolve('Oh Yeah'); const result = Promise.race([p1, p2, p3]); console.log(result); </script>
</body>
</html>

Two 、 promise key problem
2-1 1- State modification .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>Promise How the object state changes </title>
</head>
<body>
<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>
</body>
</html>
2-2 2- Whether multiple callbacks can be executed .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>Promise Specify multiple callbacks </title>
</head>
<body>
<script> 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); }) </script>
</body>
</html>

2-3 3-then Execute first or change the state to execute first .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>Promise Specify multiple callbacks </title>
</head>
<body>
<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>
</body>
</html>
2-4 4-then What is the decision of the result returned by the method .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>Promise then Method returns the characteristics of the result </title>
</head>
<body>
<script> let p = new Promise((resolve, reject) => {
resolve('ok'); }) // perform then Method let result = p.then(value => {
// console.log(value); // throw ' Something went wrong. ' // Throw an error return 521 // Return the result of right and wrong Promise Object of type // return new Promise((resolve, reject) => {
// resolve('success'); // }) }, reason => {
console.warn(reason); }) console.log(result); </script>
</body>
</html>

2-5 5- Cascade multiple operation tasks .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> How to concatenate multiple operation tasks </title>
</head>
<body>
<script> let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("ok"); // reject("err"); }, 1000) }) p.then(value => {
return new Promise((resolve, reject) => {
// resolve("success"); reject("err2") }) }).then(value => {
console.log(value); }, reason => {
console.log(reason); }).then(value => {
console.log(value); }) </script>
</body>
</html>

2-6 6- extraordinary transmission x The phenomenon .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> extraordinary transmission </title>
</head>
<body>
<script> 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); }) </script>
</body>
</html>
2-7 7- interrupt Promise chain .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> interrupt Promise chain </title>
</head>
<body>
<script> let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('OK') // reject('Err'); }, 1000); }) p.then(value => {
console.log(111); // There is but one way , interrupt Promise chain return new Promise(() => {
}); }).then(value => {
console.log(222); }).then(value => {
console.log(333); }).catch(reason => {
console.warn(reason); }) </script>
</body>
</html>
边栏推荐
- TP5 Spreadsheet Excle 表格导出
- lodash get js代码实现
- Mmdetection uses yolox to train its own coco data set
- JMeter distributed pressure measurement
- TP5 spreadsheet excel table export
- 2022 operation of simulated examination platform for tea artist (Senior) work license question bank
- Learning Tai Chi Maker - mqtt (VII) advanced mqtt theme
- Mmdetection valueerror: need at least one array to concatenate solution
- I found a JSON visualization tool artifact. I love it!
- Flink learning 2: application scenarios
猜你喜欢

PAT甲级 1023 Have Fun with Numbers

mmdetection 用yolox训练自己的coco数据集

Uni-app 之uParse 富文本解析 完美解析富文本!

Mmdetection uses yolox to train its own coco data set

JMeter distributed pressure measurement

PAT甲级 1020 Tree Traversals

Record the method of reading excel provided by unity and the solution to some pits encountered

Pat class a 1024 palindromic number

How does source insight (SI) display the full path? (do not display omitted paths) (turn off trim long path names with ellipses)

Flink learning 5: how it works
随机推荐
Anaconda3安装过程及安装后缺失大量文件,没有scripts等目录
Paddlepaddle 20 implementation and use of exponentialmovingaverage (EMA) (support static graph and dynamic graph)
超級詳細,2 萬字詳解,吃透 ES!
Uni app's uparse rich text parsing perfectly parses rich text!
Yiwen teaches you Kali information collection
Pat grade a 1021 deep root
JMeter distributed pressure measurement
平均风向风速计算(单位矢量法)
PAT甲级 1018 Public Bike Management
一文教你Kali信息收集
学习太极创客 — MQTT 第二章(三)保留消息
JMeter takes the result of the previous request as the parameter of the next request
敏捷开发篇--Agile Development-自用
Topolvm: kubernetes local persistence scheme based on LVM, capacity aware, dynamically create PV, and easily use local disk
Mmdetection uses yolox to train its own coco data set
2020:MUTANT: A Training Paradigm for Out-of-Distribution Generalizationin Visual Question Answering
Learn Tai Chi Maker - mqtt (VIII) esp8266 subscribe to mqtt topic
How does source insight (SI) display the full path? (do not display omitted paths) (turn off trim long path names with ellipses)
455. distribute biscuits [distribution questions]
JWT certification process and use cases