当前位置:网站首页>Promise and modular programming
Promise and modular programming
2022-07-02 00:33:00 【Al_ tair】
Promise And modular programming
Hello, everyone ! I'm Xiao Sheng , Let me briefly introduce some front-end knowledge .
Promise And modular programming
Promise
Basic introduction
- Conventional Ajax Asynchronous call when multiple operations are needed , This will cause multiple callback functions to be nested ( The code is not intuitive enough ) It's often said Callback Hell
- Promise Is a solution to asynchronous programming
- grammatically ,Promise It's an object , From it you can get messages for asynchronous operations
Graphic analysis

Scheme 1 :JQuery + Ajax
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="./jquery3.6.0/jquery-3.6.0.min.js"></script>
<script type="text/javascript"> $(function() {
$("#btn").click(function() {
$.getJSON( "./data/monster.json", function(data, status, XHttp) {
let {
id,name,age} = data; // Callback Hell $.getJSON( `./data/monster_detail_${
id}.json`, function(data, status, XHttp) {
console.log(data); } ) }, ) }) }) </script>
</head>
<body>
<button id="btn" type="button"> Button ( issue Ajax request )</button>
</body>
</html>
Data storage is temporarily used json File replacement
// monster.json
{
"id": 1,
"name":" The Monkey King ",
"age": 500
}
// monster_detail_1.json
{
"id": 1,
"ability":"72 change ",
"skill": " brew storms on rivers and seas ",
"address": " Huaguoshan "
}
Option two :Promise call chaining
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="jquery3.6.0/jquery-3.6.0.min.js"></script>
<script type="text/javascript"> // (resolve,reject) parameter list ( remarks :resolve,reject You can choose your own name ) // resolve: If the request succeeds , You can call resolve function // reject: If the request fails , You can call reject function let promise = new Promise((resolve, reject) => {
$.getJSON( `data/monster.json`, function(data, status, XHttp) {
console.log(data); resolve(data); } ) }).then((data => {
return new Promise((resolve, reject) => {
$.getJSON( `data/monster_detail_${
data.id}.json`, function(data, status, XHttp) {
console.log(data); resolve(data); } ) }) })).then( (data => {
return new Promise((resolve, reject) => {
$.getJSON( `data/monster_girl_${
data.girlId}.json`, function(data, status, XHttp) {
console.log(data); } ) }) }) ) </script>
</head>
<body>
</body>
</html>
Data storage is temporarily used json File replacement
// monster.json
{
"id": 1,
"name":" The Monkey King ",
"age": 500
}
// monster_detail_1.json
{
"id": 1,
"ability":"72 change ",
"skill": " brew storms on rivers and seas ",
"address": " Huaguoshan ",
"girlId":2
}
// monster_girl_2.json
{
"id": 2,
"name":"XXX",
"age": 400
}
Option three :promise Code optimization / rearrangement
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="jquery3.6.0/jquery-3.6.0.min.js"></script>
<script type="text/javascript"> // Here we will repeat the code , Pull it out , Write a method get(url, data) function get(url, data) {
return new Promise((resolve, reject) => {
$.ajax({
url: url, data: data, success(resultData) {
resolve(resultData); }, error(err) {
reject(err); } }) }) } //1. First get monster.json //2. obtain monster_detail_1.json //2. obtain monster_girl_2.json get("data/monster.json").then((resultData) => {
// The first 1 Time ajax Processing code after successful request console.log(" The first 1 Time ajax Request return data =", resultData); return get(`data/monster_detail_${
resultData.id}.json`); }).then((resultData) => {
// The first 2 Time ajax Processing code after successful request console.log(" The first 2 Time ajax Request return data =", resultData); return get(`data/monster_girl_${
resultData.girlId}.json`); }).then((resultData) => {
// The first 3 Time ajax Processing code after successful request console.log(" The first 3 Time ajax Request return data =", resultData); // continue .. }).catch((err) => {
console.log("promise Request exception =", err); }) </script>
</head>
<body>
</body>
</html>
Modular programming
Basic introduction
- Traditional non modular development has the following disadvantages :(1) name conflict (2) File dependency
- Javascript The code is getting bigger and bigger ,Javascript Introduce modular programming , Developers only need to implement the core business logic , Others can load modules that others have written
- Javascript Use " modular "(module) To realize modular programming , Solve the problem of non modular programming

CommonJS Module programming (ES5)
- Every js File is a module , Has its own scope . Variables defined in the file 、 function 、 object , It's all private , For others js The file is not visible
- CommonJS Use module.exports={} / exports={} export modular , Use let/const name = require(“xx.js”) The import module
Thought analysis

Code example
// function.js
const sum = function(a, b) {
return parseInt(a) + parseInt(b);
}
const sub = function(a, b) {
return parseInt(a) - parseInt(b);
}
let name = " Niansheng ";
let age = 18;
// module.exports = {
// sum: sum,
// sub: sub,
// name: name,
// age: age
// }
// If the property name and function / Variable / object .. The same name , It can be abbreviated
module.exports = {
sum,
sub,
name,
age
}
// use.js
const m = require("./function.js");
// Deconstruct assignment
const {
sub} = require("./function.js");
console.log(m.sub("100","200"));
console.log(m.sum(10,90));
console.log(m.name)
console.log(m.age);
console.log(sub(19,8));
ES6 Module programming
Be careful :ES6 The modularity of can't be in Node.js In the implementation of , Need to use Babel transcoding ES5 Post execution
Babel transcoding ES5 Online tools
- ES6 Use (1)export { name / object / function / Variable / Constant } (2) export Definition = (3) export default {} Export module
- Use import {} from “xx.js” / import name form “xx.js” The import module
Thought analysis

Code example
Batch export import
First export module / data :export{ object , function , Variable , Constant etc. }
const sum = function(a, b) {
return parseInt(a) + parseInt(b);
}
const sub = function(a, b) {
return parseInt(a) - parseInt(b);
}
let name = " Niansheng ";
let age = 18;
export{
sum,
sub,
name,
age
}
// Babel transcoding ES5
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sum = exports.sub = exports.name = exports.age = void 0;
var sum = function sum(a, b) {
return parseInt(a) + parseInt(b);
};
exports.sum = sum;
var sub = function sub(a, b) {
return parseInt(a) - parseInt(b);
};
exports.sub = sub;
var name = " Niansheng ";
exports.name = name;
var age = 18;
exports.age = age;
The first import module / data :import { name } from “XX.js”
import{
sum,
sub,
name,
age
} from "./common.js";
console.log(name);
console.log(age);
console.log(sub(4,2));
console.log(sum(3,4));
// Babel transcoding ES5
"use strict";
var _common = require("./common.js");
console.log(_common.name);
console.log(_common.age);
console.log((0, _common.sub)(4, 2));
console.log((0, _common.sum)(3, 4));
Export import on definition
The second kind :export object / function = {}
export const sum = function(a,b){
return parseInt(a) + parseInt(b);
}
// Babel transcoding ES5
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sum = void 0;
var sum = function sum(a, b) {
return parseInt(a) + parseInt(b);
};
exports.sum = sum;
The first import module / data :import { name } from “XX.js”
import{
sum,
} from "./common2.js";
console.log(sum(5,4));
// Babel transcoding ES5
"use strict";
var _common = require("./common2.js");
console.log((0, _common.sum)(5, 4));
Default export import
The third kind of :export default{ object , function , Variable , Constant etc. }
export default{
// Pay attention to the changes of objects var Object name = {} => Object name :{}
// Notice the change of the function const sum = function(a,b) => sum(a,b)
sum(a,b){
return parseInt(a) + parseInt(b);
},
name:" Niansheng ",
age:18
}
// Babel transcoding ES5
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = {
sum: function sum(a, b) {
return parseInt(a) + parseInt(b);
},
name: " Niansheng ",
age: 18
};
exports.default = _default;
The second is for default Export import name from “XX.js”
import m from "common3.js";
console.log(m.age);
console.log(m.name);
console.log(m.sum(3,4));
// Babel transcoding ES5
"use strict";
var _common = _interopRequireDefault(require("common3.js"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj }; }
console.log(_common.default.age);
console.log(_common.default.name);
console.log(_common.default.sum(3, 4));
边栏推荐
- 449 original code, complement code, inverse code
- SQL数据分析之流程控制语句【if,case...when详解】
- 【CTF】bjdctf_2020_babystack2
- Flow control statement of SQL data analysis [if, case... When detailed]
- 在证券账户上买基金安全吗?哪里可以买基金
- js 公共库 cdn 推荐
- 【底部弹出-选择器】uniapp Picker组件——底部弹起的滚动选择器
- Leetcode skimming: binary tree 03 (post order traversal of binary tree)
- [CTF] bjdctf 2020 Bar _ Bacystack2
- vue 强制清理浏览器缓存
猜你喜欢

牛客-练习赛101-推理小丑

LDR6035智能蓝牙音响可充可放(5.9.12.15.20V)快充快放设备充电

EMC circuit protection device for surge and impulse current protection

Barbie q! How to analyze the new game app?

LDR6035智能蓝牙音响可对手机设备持续充放电方案

Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results

Review data desensitization system
![Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]](/img/3a/cced28a2eea9f9a0d107baabd01119.png)
Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]

【底部弹出-选择器】uniapp Picker组件——底部弹起的滚动选择器

Leetcode skimming: stack and queue 06 (top k high-frequency elements)
随机推荐
时间复杂度与空间复杂度
Shell custom function
4. Object mapping Mapstercover
Ldr6035 smart Bluetooth audio can continuously charge and discharge mobile devices
B tree and b+tree of MySQL
Is it safe and reliable to open an account in Caixue school and make new debts?
How to type spaces in latex
UVM tutorial
Leetcode skimming: binary tree 01 (preorder traversal of binary tree)
启牛商学院给的证券账户安不安全?哪里可以开户
九州云与英特尔联合发布智慧校园私有云框架,赋能教育新基建
ThreadLocal内存泄漏是什么,怎么解决
Halcon knowledge: an attempt of 3D reconstruction
SQL Server Installation Guide
Example explanation: move graph explorer to jupyterlab
Asp . Text of automatic reply to NETCORE wechat subscription number
How do Lenovo computers connect Bluetooth headsets?
SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】
起床困难综合症(按位贪心)
Leetcode question brushing: stack and queue 07 (maximum value of sliding window)