当前位置:网站首页>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));
边栏推荐
- Leetcode question brushing: stack and queue 07 (maximum value of sliding window)
- BPR (Bayesian personalized sorting)
- 一个实习生的CnosDB之旅
- Record the accidental success and failure of uploading large files
- Export default the exported object cannot be deconstructed, and module Differences between exports
- How do Lenovo computers connect Bluetooth headsets?
- SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】
- PHP reads ini or env type configuration
- Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
- Ldr6035 smart Bluetooth audio can be charged and released (5.9.12.15.20v) fast charging and fast releasing device charging
猜你喜欢
Selectively inhibiting learning bias for active sampling
Windows10 install WSL (I) (wslregisterdistribution error)
Heketi record
Leetcode96 different binary search trees
Jielizhi, production line assembly link [chapter]
JS -- image to base code, base to file object
Database -- sqlserver details
GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
Leetcode skimming: stack and queue 02 (realizing stack with queue)
EMC circuit protection device for surge and impulse current protection
随机推荐
[cascade classifier training parameters] training Haar cascades
Node——Egg 创建本地文件访问接口
2023 Lexus ES products have been announced, which makes great progress this time
牛客-练习赛101-推理小丑
SQL Server Installation Guide
From 20s to 500ms, I used these three methods
PHP reads ini or env type configuration
export default 导出的对象,不能解构问题,和module.exports的区别
Asp . Text of automatic reply to NETCORE wechat subscription number
关联性——组内相关系数
下载在线视频 m3u8使用教程
Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]
【CTF】bjdctf_2020_babystack2
Use the htaccess file to prohibit the script execution permission in the directory
[template] adaptive Simpson integral
【CTF】bjdctf_2020_babystack2
2022拼多多详情/拼多多商品详情/拼多多sku详情
Jielizhi Bluetooth headset quality control and production skills [chapter]
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
Shell process control