当前位置:网站首页>关于promise then的连续链式使用问题
关于promise then的连续链式使用问题
2022-07-22 04:28:00 【tutou_girl】
今天想要多次then链式,发现自己对then的使用还比较模糊,使用过程中也出现了一些问题,特此记录一下。
function red(){
console.log("红")
}
function yellow(){
console.log("黄")
}
function green(){
console.log("绿")
}
function task(){
new Promise(function(resolve,reject){
setTimeout(() => {
red()
}, 3000);
}).then(()=>{
setTimeout(() => {
green()
Promise.resolve(1)
}, 2000);
}).then(()=>{
setTimeout(() => {
yellow()
}, 1000);
})
}
上面这种写法并不会触发then连续传递。then使用关键在于then触发必须状态改变
显然没满足,在调用red的settimeout里追加resolve()
red会打印,但不会继续打印yellow和green。因为promise状态只能改变一次,所以对于对于下一个打印green的then来说,除非上面打印red的then返回一个新的promise并且状态改变,否则不执行。
所以task修改为返回新的promise并且执行完函数后改变状态。
function task(time,color){
return new Promise(function(resolve,reject){
setTimeout(() => {
if(color==='red'){
red()
}
if(color==='green'){
green()
}
if(color==='yellow'){
yellow()
}
resolve()
}, time);
})
}
;(function(){
task(3000,'red').then(()=>{
return task(3000,'green')
}).then(()=>{
task(2000,'yellow')
})
})();
边栏推荐
- JVM memory model: class loading process
- 招股书写了“元宇宙“318次!飞天云动再战港股“元宇宙第一股“
- 用c语言编写一个函数用来删除字符串中的空格并返回空格个数
- Leetcode 172. 阶乘后的零
- How does the red team play
- Hybrid hybrid development and jsbridge
- Lesson 3 shell syntax
- CF464E The Classic Problem
- Session共享问题
- [leetcode string -- string subscript sorting] 6121. Query the number with the smallest k after cutting the number
猜你喜欢
Roson的Qt之旅#98-QML标签页控件TabView
JVM memory model: class loading process
JVM: parental delegation mechanism for class loading
盒马两大供应链中心启用 多业态商品创新研发“有后台”
Luogu_ P1112 wave number_ Thinking_ Base / construction / enumeration
ECCV 2022 | 修正FPN帶來的大目標性能損害:You Should Look at All Objects
Simulation Implementation of string
The two supply chain centers of HEMA launched the "background" of innovative research and development of multi format commodities
层序遍历BFS(广度优先)
[leetcode string -- string subscript sorting] 6121. Query the number with the smallest k after cutting the number
随机推荐
A Mobile Telematics Pattern Recognition Framework for Driving Behavior Extraction
内存管理面试问题
Simulation Implementation of string
Process and thread interview questions
Methods of checking the ranking of papers and periodicals
Distributed scheduling problem
二叉树OJ题,IO题
C server NFS shared folder building and uploading image files
Lesson 4 SSH
Win10 系统一天蓝屏好多次,怎么解决?
招股书写了“元宇宙“318次!飞天云动再战港股“元宇宙第一股“
The LAAS solution of elephant swap has risen rapidly and built a new defi2.0 protocol
Win10系统打开什么都是反应比平时慢,转圈等待1分钟如何解决?
分布式调度问题
toString()及重写的作用与应用
The Prospectus has written "yuancosmos" 318 times! Feitian Yundong fights Hong Kong stocks again "yuancosmos first share"“
CF464E The Classic Problem
Remember a composer dependency problem requires composer runtime API ^2.0.0 - > no matching package found
数据平台数据管理实践
梅科尔工作室——HarmonyOs第二次作业