当前位置:网站首页>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));
边栏推荐
- Selectively inhibiting learning bias for active sampling
- Openvino model performance evaluation tool DL workbench
- SQL Server 安裝指南
- Kyushu cloud and Intel jointly released the smart campus private cloud framework, enabling new infrastructure for education
- 基于全志H3的QT5.12.9移植教程
- How to improve data quality
- leetcode96不同的二叉搜索樹
- From 20s to 500ms, I used these three methods
- Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
- I want to ask, which is the better choice for securities companies? I don't understand. Is it safe to open an account online now?
猜你喜欢

Halcon knowledge: an attempt of 3D reconstruction

mysql之B tree 以及 B+tree

Leetcode skimming: stack and queue 01 (realizing queue with stack)

Kuberntes cloud native combat high availability deployment architecture

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

B tree and b+tree of MySQL

Leetcode96 different binary search trees

如何提升数据质量

起床困难综合症(按位贪心)

数据分析方法论与前人经验总结【笔记干货】
随机推荐
如何提升数据质量
Accelerator systems initiative is an independent non-profit organization
【opencv】train&test HOG+SVM
[template] adaptive Simpson integral
Shell process control
SQL数据分析之流程控制语句【if,case...when详解】
Barbie q! How to analyze the new game app?
@Valid参数校验不生效
Node——Egg 实现上传文件接口
【底部弹出-选择器】uniapp Picker组件——底部弹起的滚动选择器
使用多线程Callable查询oracle数据库
Leetcode skimming: binary tree 01 (preorder traversal of binary tree)
Intelligent operation and maintenance practice: banking business process and single transaction tracking
启牛学院开户安全的吗?开户怎么开?
Asp .NetCore 微信订阅号自动回复之文本篇
Windows10 install WSL (I) (wslregisterdistribution error)
记录一下大文件上传偶然成功偶然失败问题
使用htaccess文件禁止目录里的脚本执行权限
Node——Egg 创建本地文件访问接口
SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】