当前位置:网站首页>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));
边栏推荐
- Download the online video m3u8 tutorial
- Shell process control
- 【底部弹出-选择器】uniapp Picker组件——底部弹起的滚动选择器
- Windows installation WSL (II)
- The new version of graphic network PDF will be released soon
- Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
- LeetCode 0241.为运算表达式设计优先级 - DFS
- Graduation season is both a farewell and a new beginning
- LDR6035智能蓝牙音响可充可放(5.9.12.15.20V)快充快放设备充电
- How can entrepreneurial teams implement agile testing to improve quality and efficiency? Voice network developer entrepreneurship lecture Vol.03
猜你喜欢
![Flow control statement of SQL data analysis [if, case... When detailed]](/img/7b/eabb0700936d34a3a145737580be88.png)
Flow control statement of SQL data analysis [if, case... When detailed]

Intelligent operation and maintenance practice: banking business process and single transaction tracking

RFID让固定资产盘点更快更准

数据分析方法论与前人经验总结【笔记干货】

Promise和模块块化编程

Correlation - intra group correlation coefficient

How do Lenovo computers connect Bluetooth headsets?

Heketi record

USB-IF协会与各种接口的由来

Digital transformation has a long way to go, so how to take the key first step
随机推荐
Linux centos7 installation Oracle11g super perfect novice tutorial
[cascade classifier training parameters] training Haar cascades
【CTF】bjdctf_2020_babystack2
Ldr6035 smart Bluetooth audio can be charged and released (5.9.12.15.20v) fast charging and fast releasing device charging
Comprehensive usage and case questions of sub query of SQL data analysis [patient sorting]
记录一下大文件上传偶然成功偶然失败问题
使用多线程Callable查询oracle数据库
Timer和ScheduledThreadPoolExecutor的区别
Take the enclave Park as a sample to see how Yuhua and Shaoshan play the song of Chang Zhu Tan integrated development
How to improve data quality
Relevant settings of wechat applet cache expiration time (recommended)
创业团队如何落地敏捷测试,提升质量效能?丨声网开发者创业讲堂 Vol.03
BPR (Bayesian personalized sorting)
Guide d'installation du serveur SQL
Some understandings of graph convolution neural network r-gcn considering relations and some explanations of DGL official code
export default 导出的对象,不能解构问题,和module.exports的区别
Leetcode96 different binary search trees
Is the securities account given by qiniu business school safe? Where can I open an account
Operate database transactions with jpatractionmanager
Node - generate wechat permission verification configuration