当前位置:网站首页>Promise solves blocking synchronization and turns asynchronous into synchronous
Promise solves blocking synchronization and turns asynchronous into synchronous
2022-08-04 01:32:00 【Brave* Niu Niu】
Promise Solve blocking synchronization,将异步变为同步
一、样式
var p = new Promise(function(reslove,reject){
reslove()//This function is executed during construction
});
p.then(function(){
}).catch(function(){
})
————————————————————————————————————————————————————————————————————————————————————
new Promise(function(resolve,reject){
resolve();
}).then(function(){
// resolve时执行
},function(){
// reject时执行
})
Promise
Requires instantiation to complete creating onePromise
对象- 在
Promise
A callback function is passed in the instantiated constructor - 回调函数中有两个参数,一个是
resolve
,一个是reject
- 当成功后调用
resolve
函数,失败后调用reject
函数 - 并且可以通过
resolve
或者reject
函数传递一个参数 - 给
Promise
The instantiated object executes two methods one isthen
,一个 是catch
- There are two callback functions in these two methods,当执行
resolve
时,调用then
中回调函数,当执行reject
时调用catch
中的回调函数 - 在PromiseCan only be called once in an instantiated constructresolve或者一次 reject,调用一次后,Call either one againresolve或者reject都是无效的
The sequential output is asynchronousabc
new Promise(function(resolve,reject){
setTimeout(function(){
resolve()
},1000)
}).then(function(){
console.log('a');
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve()
},500)
})
}).then(function(){
console.log('b');
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve()
},1000)
})
}).then(function(){
console.log('c');
})
输出:
a
b
c
Sequentially output asynchronous traffic lights
function setTime(time){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve()
},time)
})
}
setTime(100).then(function(){
console.log('黄灯');
return setTime(1000)
}).then(function(){
console.log('绿灯');
return setTime(500)
}).then(function(){
console.log('红灯');
})
封装返回一个Promise对象
//The secondary function returns onePromise对象
function setTime(time){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve();
},time);
})
}
Promise对象执行方法then
setTime().then(function(){
console.log('aaa');
})
//aaa
chained usePromise
function setTime(time){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve();
},time);
})
}
setTime(500).then(function(){
console.log('aaa');
return setTime(1000);
}).then(function(){
console.log('bbb');
return setTime(100);
}).then(function(){
console.log('ccc');
})
aaa
bbb
ccc
预加载图片
Make async a blocking sync
function loadImage(src){
return new Promise(function(resolve,reject){
var img = new Image();
img.src = src;
/* Execute the code when loading is complete */
img.onload = function(){
/* 执行resolve回调函数,传入参数img对象 */
resolve(img)
}
})
}
var arr = [];
/* PromiseThe callback function is executed when the object is constructedresolve,而执行resolve会调用方法then中的回调函数 */
loadImage("./img/img_15.JPG").then(img =>{
arr.push(img)
return loadImage("./img/img_16.JPG")
}).then(img =>{
arr.push(img)
return loadImage("./img/img_17.JPG")
}).then(img =>{
arr.push(img)
console.log(arr);
})
function loadImage(src){
return new Promise(function(resolve,reject){
var img = new Image();
img.src = src;
img.onload = function(){
resolve(img)
}
img.onerror = function(){
reject(src)
}
})
}
//Execute code on error
var arr = [];
loadImage("./img/img_11.JPG").then(img =>{
arr.push(img)
}).catch(function(src){
console.error("error:"+src);
})
连续then时,Equivalent to automatically creating onereturn promise并且执行resolve
new Promise(function(resolve,reject){
setTimeout(function(){
resolve();
},500);
}).then(function(){
console.log("aa");
// 连续then,并没有return新的Promise时,相当于自动return Promise执行了resolve
// return new Promise(function(resolve,reject){
// resolve();
// })
}).then(function(){
console.log("bb");
})
Two shortcuts
Promise.resolve().then(function(){
})
Promise.reject().catch(function(){
})
The image is preloaded as a whole
- Use all async firstPromiseAfter packaging, put it in an array
- 然后通过Promise.all传入这个数组,这时候
- All execute asynchronouslyresolveThe parameters passed in will be followed
- order in an array,并且通过thenThe parameter is returned
function loadImage(src){
return new Promise(function(resolve,reject){
var img = new Image();
img.src = src;
img.onload = function(){
resolve(img)
}
img.onerror = function(){
reject(src)
}
})
}
arr = [];
for(var i=15;i<19;i++){
var p = loadImage(`./img/img_${
i}.JPG`);
arr.push(p);
}
console.log(arr);
Promise.all(arr).then(function(list){
list.forEach(item=>console.log(item));
})
Whoever loads first will be shown
Promise.race(arr).then(function(img){
console.log(img);
})
Simplest asynchronous loadingasync,awiat
function loadImage(src){
return new Promise(function(resolve,reject){
var img = new Image();
img.src = src;
img.onload = function(){
resolve(img)
}
img.onerror = function(){
reject(src)
}
})
}
init();
async function init(){
arr = [];
for(var i=15;i<19;i++){
/*Automatic waiting will beloadImage函数执行的resolveThe result value of the function is returned top*/
var p = await loadImage(`./img/img_${
i}.JPG`);
arr.push(p);
}
console.log(arr);
}
边栏推荐
猜你喜欢
静态文件快速建站
How to find the cause of Fiori Launchpad routing errors by single-step debugging
typescript54 - generic constraints
持续投入商品研发,叮咚买菜赢在了供应链投入上
typescript51 - basic use of generics
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
ASP.NET 获取数据库的数据并写入到excel表格中
this巩固训练,从两道执行题加深理解闭包与箭头函数中的this
七夕佳节即将来到,VR全景云游为你神助攻
字符串变形
随机推荐
FeatureNotFound( bs4.FeatureNotFound: Couldn‘t find a tree builder with the features you requested:
.NET Static Code Weaving - Rougamo Release 1.1.0
简单的线性表的顺序表示实现,以及线性表的链式表示和实现、带头节点的单向链表,C语言简单实现一些基本功能
Installation and configuration of nodejs+npm
Analysis of usage scenarios of mutex, read-write lock, spin lock, and atomic operation instructions xaddl and cmpxchg
typescript48-函数之间的类型兼容性
typescript56 - generic interface
【正则表达式】笔记
esp32发布机器人电池电压到ros2(micro-ros+CoCube)
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
typescript53-泛型约束
字符串的排列
【无标题】
initramfs详解----添加硬盘驱动并访问磁盘
nodejs+npm的安装与配置
typescript52-简化泛型函数调用
TensoFlow学习记录(二):基础操作
持续投入商品研发,叮咚买菜赢在了供应链投入上
VR panorama shooting online exhibition hall, 3D panorama brings you an immersive experience
typescript51 - basic use of generics