当前位置:网站首页>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时执行
})
PromiseRequires instantiation to complete creating onePromise对象- 在
PromiseA callback function is passed in the instantiated constructor - 回调函数中有两个参数,一个是
resolve,一个是reject - 当成功后调用
resolve函数,失败后调用reject函数 - 并且可以通过
resolve或者reject函数传递一个参数 - 给
PromiseThe 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);
}
边栏推荐
- MySQL回表指的是什么
- 【Untitled】
- Analysis: What makes the Nomad Bridge hack unique
- Apache DolphinScheduler新一代分布式工作流任务调度平台实战-中
- GNSS[0]- Topic
- html select标签赋值数据库查询结果
- nodejs安装及环境配置
- 螺旋矩阵_数组 | leecode刷题笔记
- LeetCode third topic (the Longest Substring Without Repeating Characters) trilogy # 3: two optimization
- How to copy baby from Taobao (or Tmall store) through API interface to Pinduoduo interface code docking tutorial
猜你喜欢

Tanabata festival coming, VR panoramic look god assists for you
![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.
![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.

jmeter distributed stress test

nodejs切换版本使用(不需要卸载重装)

Array_Sliding window | leecode brushing notes

GraphQL背后处理及执行过程是什么

敏捷交付的工程效能治理

Installation and configuration of nodejs+npm

redis中常见的问题(缓存穿透,缓存雪崩,缓存击穿,redis淘汰策略)
随机推荐
工程制图复习题(带答案)
在Activity中获取另一个XML文件的控件
快速入门EasyX图形编程
Analysis of usage scenarios of mutex, read-write lock, spin lock, and atomic operation instructions xaddl and cmpxchg
JS 从零教你手写节流throttle
多线程 之 JUC 学习篇章一 创建多线程的步骤
持续投入商品研发,叮咚买菜赢在了供应链投入上
Web3 security risks daunting?How should we respond?
HBuilderX的下载安装和创建/运行项目
GNSS[0]- Topic
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之三:两次优化
nodejs安装及环境配置
持续投入商品研发,叮咚买菜赢在了供应链投入上
vxe-table 从页面批量删除数据 (不动数据库里的数据)
114. How to find the cause of Fiori Launchpad routing error by single-step debugging
C语言:学生管理系统(链表版)
ASP.NET 获取数据库的数据并写入到excel表格中
TensoFlow学习记录(二):基础操作
- heavy OpenCV 】 【 mapping
GraphQL背后处理及执行过程是什么