当前位置:网站首页>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));
边栏推荐
- Three methods of finding inverse numbers
- From 20s to 500ms, I used these three methods
- Windows installation WSL (II)
- Node -- egg creates a local file access interface
- leetcode96不同的二叉搜索树
- Leetcode 96 différents arbres de recherche binaires
- 股票开户哪个证券公司比较安全
- GCC compilation
- Leetcode question brushing: stack and queue 07 (maximum value of sliding window)
- I would like to ask, which securities is better for securities account opening? Is it safe to open a mobile account?
猜你喜欢

Niuke - Practice 101 - reasoning clown

Promise和模块块化编程

JS -- image to base code, base to file object

Take the enclave Park as a sample to see how Yuhua and Shaoshan play the song of Chang Zhu Tan integrated development

It's nothing to be utilitarian!

How can entrepreneurial teams implement agile testing to improve quality and efficiency? Voice network developer entrepreneurship lecture Vol.03

Download the online video m3u8 tutorial

The new version of graphic network PDF will be released soon

Review data desensitization system

2022 pinduoduo details / pinduoduo product details / pinduoduo SKU details
随机推荐
ERP项目施行计划的目的是什么?
Take the enclave Park as a sample to see how Yuhua and Shaoshan play the song of Chang Zhu Tan integrated development
基于全志H3的QT5.12.9移植教程
SQL数据分析之流程控制语句【if,case...when详解】
Digital transformation has a long way to go, so how to take the key first step
Barbie q! How to analyze the new game app?
SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】
LDR6035智能蓝牙音响可对手机设备持续充放电方案
[cascade classifier training parameters] training Haar cascades
Download the online video m3u8 tutorial
JS -- image to base code, base to file object
【CTF】bjdctf_2020_babystack2
[CTF] bjdctf 2020 Bar _ Bacystack2
How to open an account for individual stock speculation? Is it safe?
【opencv】train&test HOG+SVM
【微信授权登录】uniapp开发小程序,实现获取微信授权登录功能
Is it safe to choose mobile phone for stock trading account opening in Beijing?
RFID让固定资产盘点更快更准
Is it safe and reliable to open an account in Caixue school and make new debts?
An intern's journey to cnosdb