当前位置:网站首页>Promise understanding has used promise to realize picture preloading (sequential loading)
Promise understanding has used promise to realize picture preloading (sequential loading)
2022-06-12 12:05:00 【Mustang (Mustang)】
1、 First, let's introduce how to preload the function image of the object
var num=3;// This is defined as 3 Because the picture name defines , The name of the picture is usually fixed , Change the same position to a different number
var list=[];// The empty array is used to store the
init();
function init(){
var img=new Image(); // Create a Image object
img.addEventListener("load",loadHandler);// to img Object to add a listening event , yes load Loading event
img.src="img/3-.jpg";//img.src Property value assignment ( The name of this picture is )
}
function loadHandler(e){ // After the loading
list.push(this.cloneNode(false));// towards list,push Elements in parentheses , The elements in parentheses are derived from shallow copying ,cloneNode Shallow copy , Syntax is the target object .cloneNode(false), here this yes img
num++;
if(num>8){ // When more than 8 The following statement will not be executed , Otherwise, continue to execute the following statement
console.log(list);// Print view
return;
}
this.src="img/"+num+"-.jpg";// The address of the picture ( Depends on you. HTML And img The relative address of the picture ),
}

2、 Callback hell writing , Process writing
var list=[];
var img=new Image();
img.src="img/3-.jpg";
img.onload=function(){
list.push(this);
img=new Image();
img.src="img/4-.jpg";
img.onload=function(){
list.push(this);
img=new Image();
img.src="img/5-.jpg";
img.onload=function(){
list.push(this);
img=new Image();
img.src="img/6-.jpg";
img.onload=function(){
list.push(this);
img=new Image();
img.src="img/7-.jpg";
img.onload=function(){
list.push(this);
img=new Image();
img.src="img/8-.jpg";
img.onload=function(){
list.push(this);
}
}
}
}
}
}
console.log(list);

3、promise Solve callback hell
function loadImg(_src){ // Pass in address parameters
// resolve The statement that is executed when the flag is successful
// reject The statement executed when the flag fails
// It can be written in a different way :var Promise=new Promise();// return Promise return promise , It is usually written in the following way , Because it simply doesn't declare any other variables
return new Promise(function(resolve,reject){
var img=new Image();
img.src=_src;
img.onload=function(){// Loading successful
resolve(img);
};
img.onerror=function(){// Loading failed
reject(" Load error ");
}
})
}
var list=[];
loadImg("img/3-.jpg").then(function(img){
list.push(img.width);
return loadImg("img/4-.jpg");
}).then(function(img){
list.push(img.width);
return loadImg("img/5-.jpg");
}).then(function(img){
list.push(img.width);
return loadImg("img/6-.jpg");
}).then(function(img){
list.push(img.width);
return loadImg("img/7-.jpg");
}).then(function(img){
list.push(img.width);
return loadImg("img/8-.jpg");
}).then(function(img){
list.push(img.width);
console.log(list);
})

4、all
all Call all promise asynchronous , Execute after all asynchronies are completed then The function in
var arr=[];
var list=[];
function loadImg(_src){ // Pass in address parameters
// resolve The statement that is executed when the flag is successful
// reject The statement executed when the flag fails
// It can be written in a different way :var Promise=new Promise();// return Promise return promise , It is usually written in the following way , Because it simply doesn't declare any other variables
return new Promise(function(resolve,reject){
var img=new Image();
img.src=_src;
img.onload=function(){// Loading successful
resolve(img);
};
img.onerror=function(){// Loading failed
reject(" Load error ");
}
})
}
for(var i=3;i<9;i++){
arr.push(loadImg("img/"+i+"-.jpg"))
}
Promise.all(arr).then(function(list){
console.log(list,'1');
})
**
5、race The understanding of the
race All asynchronous operations , Whoever finishes first will execute
**

6、resolve Call directly
The function is asynchronous 
summary :
What is it?
promise
Promise Is a solution to asynchronous programming .
characteristic
1、 The state of the object is not affected by the outside world .Promise The object represents an asynchronous operation , Yes 3 Medium state :Pending( Have in hand )、Fulfilled( Have succeeded )、Rejected( Failed ). Only the result of an asynchronous operation can determine the current state , No other operation can change this state .
2、 Once the state changes, it won't change again , You can get that at any time .Prmise There are only two possibilities for the state of an object to change : from Pending To Fulfilled, from Pending To Rejected. As long as those two things happen , The state is frozen , It won't change again , But keep this result all the time , This is the case Reaolved( Have to finalize the design )
Advantages and disadvantages
advantage :
1、 Express the asynchronous operation in the process of synchronous operation , Avoid nesting callback functions
2、 Unified interface , It is easier to control asynchronous operations
shortcoming
1、 Can't cancel Promise, Once created, it will be executed immediately .
2、 If you do not set the callback function , Errors cannot be reflected externally
3、 When in Pending In the state of , It is impossible to know which stage it has reached ( Is it just beginning or about to finish )
Basic usage
promise An object is a constructor , Used to generate promise example
adopt new promise Create a promise object , There is a parameter , Parameter is a callback function , There is... In the callback function 2 Parameters ,resolve,reject.
resolve() The method called when the asynchronous execution succeeds ,reject() Method called when asynchrony fails .
besides promise There is one then Method , Execute the first callback function when successful , Execute the second callback function when it fails . The second callback function can also be passed through promise object .catch call .
for example :.then(function(res){ }.function( ){ }) It's a way of writing
.then(function(){}).catch(function(){ })

Promise The argument to the constructor is a function , This function takes two arguments , Are also functions , Namely resolve and reject.resolve The role of the Promise The state of the object never completes and becomes successful , Called when the asynchronous operation succeeds , The result of the asynchronous operation is passed as a parameter , and reject It is used in the case of failure . When Promise After instance generation , It can be used then Methods specify Resolve State and Rejected Callback function for state ..then The first function parameter of the object is to handle resolve The situation of , The second function argument is to handle reject The situation of
then The function of the method is to Promise Instance adds a callback function when the state changes . The return is still a Promise object , But it is a new object , It is no longer the original instance . Therefore, the chain type can be used . A very important point : It's a chain then You can specify a set of callback functions to be called in order , hinder then Wait for the front then( That's new Promise Execute after the object state changes , If the front then Status is resolve Then execute the first parameter function , Otherwise, the second parameter function is executed ),promise.then() A micro task that belongs to an asynchronous task , When a micro task is executed , He will do it all in sequence **
Summarize knowledge points :
promise then(function(){},function(){}) perhaps then(function(){}).catch(function(){})
all Use
race Use
resolve Direct call to
边栏推荐
- 【Leetcode】416. Split equal sum subset
- Reasons for SSL introduction and encryption steps
- ARM指令集之乘法指令
- Decision tree of machine learning
- [foundation of deep learning] back propagation method (1)
- In navigation, the solution of adding borders to affect the layout
- this的指向
- Relation entre les classes et à l'intérieur des classes de classification vidéo - - Régularisation
- [foundation of deep learning] learning of neural network (4)
- Who moved my package lock
猜你喜欢

Left and right cases + rotating pictures of small dots + no time

Asynchronous path processing

Design of secure chat tool based on C #

Batch load/store instructions of arm instruction set

Must do skill -- use ffmpeg command to quickly and accurately cut video

Reprint --win10 open the task manager to solve the blue screen problem

Ros- resolve error "tf2\u buffer\was not declared in this scope"

【深度学习基础】反向传播法(1)

Create servlet project

寻找两个有序数组的中位数(LeetCode 4)
随机推荐
Rich text editor copying pictures in word documents
Load/store memory access instruction of arm instruction set (1)
object.defineProperty 基本使用
How to determine the relationship between home page and search? Relationship between homepage and search
【QNX Hypervisor 2.2 用户手册】4 构建QNX Hypervisor系统
Node crawler puppeter usage
ARM指令集之Load/Store访存指令(一)
Conversion between ROS map picture pixels and map coordinate system coordinates
Load/store access instruction of arm instruction set (2)
第六章 数据类型(五)
TinyMCE realizes automatic uploading of pasted pictures
QT添加QObject类(想使用信号和槽)遇到的问题汇总,亲测解决有效error: undefined reference to `vtable for xxxxxx(你的类名)‘
邻居子系统之ARP协议数据处理过程
Tpage design
QML first day
Judge whether the network file exists, obtain the network file size, creation time and modification time
Why is there no traffic after the launch of new products? How should new products be released?
ARM指令集之乘法指令
QT adds a summary of the problems encountered in the QObject class (you want to use signals and slots) and solves them in person. Error: undefined reference to `vtable for xxxxx (your class name)‘
[database] SQLite version upgrade and downgrade