当前位置:网站首页>How promise instance solves hell callback
How promise instance solves hell callback
2022-07-28 09:29:00 【Front end program】
List of articles
Tips : This afternoon, colleagues in the company asked about sending network requests conditionally
The scene is as follows : Initiate the first request , After getting the first request ; To continue sending the second request ; After the second request is sent , Use the second parameter and the third request .
The above scenario is the problem of hell callback , At this time, we can use encapsulation Promise Methods to solve what we have been doing .then() Write the request in , It also makes our code more readable .
Tips : After writing the article , Directories can be generated automatically , How to generate it, please refer to the help document on the right
List of articles
One 、 Hell callback ( Code case ):
//fetch Is our network request ( Here are simulations and examples )
fetch("http://127.0.0.0:3000/").then((res) => {
console.log("yi !");
fetch("http://127.0.0.0:3000/diyi").then((res) => {
console.log("er !!");
fetch("http://127.0.0.0:3000/dier").then((res) => {
console.log("san !!!");
});
});
});
The result printed here is :
for the first time :yi !
The second time :er !!
third time :san !!!
Two 、 What is? Promise?
Promise: It's a constructor , Used to deliver asynchronous operation messages , call chaining , Avoid nested callback functions .
- promise Receive two function parameters ,resolve and reject, It represents the callback after successful execution of asynchronous operation and the callback after failure
- Promise There are three states :pending Have in hand 、resolve Completed 、rejected Failed , These states can only be determined by pending ->
resolved, pending -> rejected, once promise The instance has changed , Can't change , You can get that at any time
3、 ... and 、 Use Promise Solve hell callback :
1. Write a return Promise Example method
The code analysis diagram is as follows

The code is as follows ( Example ):
//requestMethods It's a function ( Method ), It can deliver a,b,c Three parameters
function requestMethods(a, b, c) {
// This step is to new Promise Return to requestMethods function
return new Promise((resolve, reject) => {
// When b=2(b It is the result of the second request ),c=3 When it comes to execution
if (b == 2 && c == 3) {
setTimeout(() => {
resolve(10);
}, 2000);
return;
}
// When a=1(a It's a request to get the result ),b=2 When it comes to execution
if (a == 1 && b == 2) {
setTimeout(() => {
resolve(b);
}, 2000);
return;
}
// When a=1 When it comes to execution
if (a == 1) {
resolve(a);
return;
}
});
}
2. call requestMethods() View results
The code analysis diagram is as follows

The code is as follows ( Example ):
// This is the first network request ( simulation )
requestMethods((a = 1))
// The first request result then Callback function
.then((res) => {
console.log(res, "a");
// This is the second network request ( simulation )
return requestMethods((a = res), (b = 2));
})
// The result of the second request
.then((res) => {
console.log(res, "b");
// This is the third network request ( simulation )
return requestMethods((a = 1), (b = res), (c = 3));
})
// The third request result
.then((res) => {
console.log(res, "c");
});
summary
Tips : Here is a summary of the article : Overall Api It's very easy to understand , I explained it to my colleagues and understood , I hope this article is useful to you , At the same time, writing articles can also improve my own mastery , I hope everyone can be very !!!!!!! come on. !!!!!!
边栏推荐
- 负数的十六进制表示
- MATLAB的符号运算
- 2022年危险化学品经营单位安全管理人员上岗证题目及答案
- MySQL 8.0.30 GA
- 2022 safety officer-b certificate examination simulated 100 questions and answers
- final关键字和枚举类型
- Openshift 4 - use verticalpodautoscaler to optimize application resource request and limit
- RGB-T追踪——【多模态融合】Visible-Thermal UAV Tracking: A Large-Scale Benchmark and New Baseline
- 【JVM】JVM表示浮点数
- Dn-detr paper accuracy, and analyze its model structure & 2022 CVPR paper
猜你喜欢

AMQ streams (1) of openshift 4 - multiple consumers receive data from partition

2022年安全员-B证考试模拟100题及答案

Bluetooth technology | the total scale of charging piles in Beijing will reach 700000 in 2025. Talk about the indissoluble relationship between Bluetooth and charging piles

IP protocol of network layer

MQTT.js 入门教程:学习笔记

一款入门神器TensorFlowPlayground

Openshift 4 - use verticalpodautoscaler to optimize application resource request and limit
![[C language] detailed explanation sequence table (seqlist)](/img/60/c8cee6a6afe57247aba583291cc99b.png)
[C language] detailed explanation sequence table (seqlist)

Network engineering -- ranking of Chinese universities in Soft Science

Technology sharing | quick intercom integrated dispatching system
随机推荐
5 operators, expressions, and statements
Dn-detr paper accuracy, and analyze its model structure & 2022 CVPR paper
1.5 merge\rebase\revert\stash\branch
Common prototype methods of canvas and the application of drawing pictures
Leetcode 452. minimum number of arrows to burst balloons (medium)
IJCAI 2022 | 图结构学习最新综述:研究进展与未来展望
Magic brace- [group theory] [Burnside lemma] [matrix fast power]
[autosar-rte] - introduction of 2-component, component and VFB
正则表达式为十六进制数字?
负数的十六进制表示
final关键字和枚举类型
IntelliJ idea associated database
VR全景拍摄,助力民宿多元化宣传
[C language] detailed explanation sequence table (seqlist)
树上启发式合并
leetcode 452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球(中等)
js数组去重,id相同对某值相加合并
v-bind指令的详细介绍
[multithreading] the underlying principle of println method
FPGA development learning open source website summary