当前位置:网站首页>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);
}
边栏推荐
- GraphQL背后处理及执行过程是什么
- Electronics manufacturing enterprise deployment WMS what are the benefits of warehouse management system
- 无代码7月热讯 | 微软首推数字联络中心平台;全球黑客马拉松...
- 静态文件快速建站
- How to find the cause of Fiori Launchpad routing errors by single-step debugging
- Flink jdbc connector 源码改造sink之 clickhouse多节点轮询写与性能分析
- 分析:Nomad Bridge黑客攻击的独特之处
- Tanabata festival coming, VR panoramic look god assists for you
- typescript50 - type specification between cross types and interfaces
- 【正则表达式】笔记
猜你喜欢

Deng Qinglin, Alibaba Cloud Technical Expert: Best Practices for Disaster Recovery across Availability Zones and Multiple Lives in Different Locations on the Cloud

Demand analysis of MES management system in electronic assembly industry

typescript50-交叉类型和接口之间的类型说明

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

Modulo operation (MOD)

jmeter distributed stress test

typescript57-数组泛型接口

JS 保姆级贴心,从零教你手写实现一个防抖debounce方法

typescript52-简化泛型函数调用

【链路聚合原理及配置】
随机推荐
Use nodejs switch version (no need to uninstall and reinstall)
jmeter分布式压测
Google Earth Engine - Calculates the effective width of rivers using publicly available river data
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
电子制造企业部署WMS仓储管理系统的好处是什么
C # WPF equipment monitoring software (classic) - the next
nodejs installation and environment configuration
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
字符串变形
jmeter跨平台运行csv等文件
Quickly build a website with static files
无代码7月热讯 | 微软首推数字联络中心平台;全球黑客马拉松...
js函数防抖和函数节流及其使用场景
谁说程序员不懂浪漫,表白代码来啦~
【日志框架】
动态内存二
[store mall project 01] environment preparation and testing
appium软件自动化测试框架
- heavy OpenCV 】 【 mapping
贴纸拼词 —— 记忆化搜索 / 状压DP