当前位置:网站首页>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);
}
边栏推荐
猜你喜欢
typescript58 - generic classes
【虚拟户生态平台】虚拟化平台安装时遇到的坑
typescript53-泛型约束
Android interview questions and answer analysis of major factories in the first half of 2022 (continuously updated...)
typescript52 - simplify generic function calls
appium软件自动化测试框架
企业虚拟偶像产生了实质性的价值效益
pygame 中的transform模块
nodejs+express realizes the access to the database mysql and displays the data on the page
redis中常见的问题(缓存穿透,缓存雪崩,缓存击穿,redis淘汰策略)
随机推荐
数组_滑动窗口 | leecode刷题笔记
js中常用的几种遍历处理数据的方法梳理
2022 China Computing Power Conference released the excellent results of "Innovation Pioneer"
工程制图复习题
GraphQL背后处理及执行过程是什么
typescript56-泛型接口
.NET静态代码织入——肉夹馍(Rougamo) 发布1.1.0
typescript54 - generic constraints
FeatureNotFound( bs4.FeatureNotFound: Couldn‘t find a tree builder with the features you requested:
boot issue
typescript48-函数之间的类型兼容性
typescript56 - generic interface
C 学生管理系统_添加学生
静态/动态代理模式
LeetCode third topic (the Longest Substring Without Repeating Characters) trilogy # 3: two optimization
字符串的排列
initramfs详解----添加硬盘驱动并访问磁盘
如何通过单步调试的方式找到引起 Fiori Launchpad 路由错误的原因试读版
KunlunBase 1.0 is released!
虚拟机CentOS7中无图形界面安装Oracle