当前位置:网站首页>Promise 解决阻塞式同步,将异步变为同步
Promise 解决阻塞式同步,将异步变为同步
2022-08-04 01:24:00 【勇敢*牛牛】
Promise 解决阻塞式同步,将异步变为同步
一、样式
var p = new Promise(function(reslove,reject){
reslove()//在构造的时候就执行这个函数了
});
p.then(function(){
}).catch(function(){
})
————————————————————————————————————————————————————————————————————————————————————
new Promise(function(resolve,reject){
resolve();
}).then(function(){
// resolve时执行
},function(){
// reject时执行
})
Promise需要实例化完成创建一个Promise对象- 在
Promise实例化的构造函数中传入一个回调函数 - 回调函数中有两个参数,一个是
resolve,一个是reject - 当成功后调用
resolve函数,失败后调用reject函数 - 并且可以通过
resolve或者reject函数传递一个参数 - 给
Promise实例化的对象执行两个方法一个是then,一个 是catch - 这两个方法中有两个回调函数,当执行
resolve时,调用then中回调函数,当执行reject时调用catch中的回调函数 - 在Promise实例化的构造中只能调用一次resolve或者一次 reject,调用一次后,再次调用任何一个resolve或者reject都是无效的
顺序输出异步abc
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
顺序输出异步红绿灯
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对象
//次函数返回一个Promise对象
function setTime(time){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve();
},time);
})
}
Promise对象执行方法then
setTime().then(function(){
console.log('aaa');
})
//aaa
连缀使用Promise
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
预加载图片
让异步变成一个阻塞式同步
function loadImage(src){
return new Promise(function(resolve,reject){
var img = new Image();
img.src = src;
/* 加载完成时执行一下代码 */
img.onload = function(){
/* 执行resolve回调函数,传入参数img对象 */
resolve(img)
}
})
}
var arr = [];
/* Promise对象构造的时候执行了回调函数resolve,而执行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)
}
})
}
//错误时执行代码
var arr = [];
loadImage("./img/img_11.JPG").then(img =>{
arr.push(img)
}).catch(function(src){
console.error("error:"+src);
})
连续then时,相当于自动创建一个return 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");
})
两种快捷写法
Promise.resolve().then(function(){
})
Promise.reject().catch(function(){
})
图片整体预加载
- 先把所有异步使用Promise封装后放在一个数组中
- 然后通过Promise.all传入这个数组,这时候
- 所有异步执行resolve传入的参数就会被按照
- 顺序放在一个数组中,并且通过then中参数返回
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));
})
谁先加载完就显示谁
Promise.race(arr).then(function(img){
console.log(img);
})
最简点的异步加载async,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++){
/*自动等待将loadImage函数执行的resolve函数的结果值返回给p*/
var p = await loadImage(`./img/img_${
i}.JPG`);
arr.push(p);
}
console.log(arr);
}
边栏推荐
- nodejs安装及环境配置
- Installation and configuration of nodejs+npm
- pygame 中的transform模块
- VR全景拍摄线上展馆,3D全景带你沉浸体验
- 如何通过API接口从淘宝(或天猫店)复制宝贝到拼多多接口代码对接教程
- Deng Qinglin, Alibaba Cloud Technical Expert: Best Practices for Disaster Recovery across Availability Zones and Multiple Lives in Different Locations on the Cloud
- GNSS文章汇总
- 114. How to find the cause of Fiori Launchpad routing error by single-step debugging
- LDO investigation
- Array_Sliding window | leecode brushing notes
猜你喜欢

【日志框架】

nodejs installation and environment configuration

Analysis of usage scenarios of mutex, read-write lock, spin lock, and atomic operation instructions xaddl and cmpxchg

LeetCode third topic (the Longest Substring Without Repeating Characters) trilogy # 3: two optimization

114. How to find the cause of Fiori Launchpad routing error by single-step debugging

互斥锁、读写锁、自旋锁,以及原子操作指令xaddl、cmpxchg的使用场景剖析
![Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.](/img/10/87c0bedd49b5dce6fbcd28ac361145.png)
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.

Vant3 - click on the corresponding name name to jump to the next page corresponding to the location of the name of the TAB bar

Use nodejs switch version (no need to uninstall and reinstall)

网络带宽监控,带宽监控工具哪个好
随机推荐
dynamic memory two
.NET Static Code Weaving - Rougamo Release 1.1.0
typescript52-简化泛型函数调用
即席查询——Presto
MATLAB三维绘图命令plot3入门
typescript50 - type specification between cross types and interfaces
outputBufferIndex = mDecode.dequeueOutputBuffer(bufferInfo, 0) 一直返回为-1
nodejs install multi-version version switching
一个注解替换synchronized关键字:分布式场景下实现方法加锁
Getting started with MATLAB 3D drawing command plot3
字符串变形
JS 从零教你手写节流throttle
分析:Nomad Bridge黑客攻击的独特之处
typescript51 - basic use of generics
动态内存二
typescript56 - generic interface
initramfs详解----添加硬盘驱动并访问磁盘
Use nodejs switch version (no need to uninstall and reinstall)
TensoFlow学习记录(二):基础操作
敏捷交付的工程效能治理