当前位置:网站首页>Promise object
Promise object
2022-07-28 02:58:00 【M78_ Domestic 007】
I'm learning Promise Before , We know what is synchronous and what is asynchronous .
Sync : Scripts are executed in order , After performing the current task , To carry out the next task .
Write a code description to understand
<script>
console.log(1);
for (let i = 0; i < 1000; i++) {
}
console.log(3);
// The result of this code printing is 1 3
// But the console doesn't print out at the first time 3, It waits for The loop is finished 1000 Later , Then print 3
</script>asynchronous : Not in the order of the code , A task has one or more Callback function (callback), After the end of the previous mission , Not to perform the latter task , Instead, execute the callback function , The latter task is executed before the end of the previous task , So the execution order of the program is inconsistent with the order of the tasks 、 Asynchronous .
Want to learn asynchronous programming , You must be proficient in callback functions , Asynchronous design idea is callback function , If you don't learn the callback function well, you can learn it well first , Learn this knowledge again .
Promise
Promise stay ES5 There it is ES6 Write the standard directly .
Promise It's a constructor , Not an asynchronous non blocking function , use new Promise Create a data container .
Compare with the data learned before :
Map Set Array Object Passively generate data , Add data to it ,Promise Actively generate data without adding data .
Promise The data containers created are then function , When this data container fetches data, it uses then function , It is a non blocking asynchronous function , It's official 、 Browser bottom layer c/c++ Written , Common non blocking asynchronous functions are setTimeout、node.js Medium readFile() ; We designed our own asynchronous function , Absolutely blocking asynchronous functions , Because it is js Written in scripting language , Cannot execute at the same time , Meaning the code must execute the previous line before it can execute the next line .
Just use it then function :
<script>
// Create a Peomise object
var p = new Promise(function(n1,n2){// there n1,n2 Is the callback function
var n=10
n1(n)// Called n1 Give Way Promise Data is generated internally
})
// At this point we need to use then Function to get the generated data
p.then(function(data){
console.log(data) //10
})
</script>Be careful : then The return value of the function is a new Promise object , yes then The return value of the incoming callback function
There are two situations for the return value of the incoming callback function :
1、 If the return value is a Promise object , So that's it ;
2、 If not one Promise object , Then the result of the function will be packaged as a generated data Promise object ;
Next, we will explain the n1,n2 What is it? ?
n1 Written in many documents resolve, Represents the callback function after the asynchronous operation is successfully executed ;
n2 Is written as reject, Represents the callback function after the asynchronous operation fails
In our actual development , We need to get data from the back end , Sometimes the data obtained is correct , Now we use n1 To trigger , Give Way Promise Generate correct data in ; Sometimes the data obtained is wrong , To use n2 To trigger , inform Promise The system is the data of business errors .
Specific code description :
<script>
// Create a Peomise object
var p = new Promise(function(n1,n2){// there n1,n2 Is the callback function
var data = {
code: 404,
info: " Fake data On behalf of future business Generated data Like network requests "
}
// Judge whether the data is correct Here is the wrong data use n2 Trigger
if (data.code == 404) {
n2(data.info) // Trigger
// After this program runs, the program will report an error
// except n2 Can trigger Promise Generate wrong data You can also throw errors directly
// throw " I am the wrong data in business "
} else if (data.code == 200) {
n1(data.info)
}
})
// The following code is no longer executed
p.then(function(data){
console.log(data)
})
console.log(111)
</script>The situation of the console :
We can't let the program we write get stuck here , We're going to introduce Promise Another method of the created object catch.
catch Used to catch errors , Its underlying principle is try-catch sentence . Very simple to use , Use the code of the last example , Only need then After the function catch Functions
<script>
// Create a Peomise object
var p = new Promise(function(n1,n2){// there n1,n2 Is the callback function
var data = {
code: 404,
info: " Fake data On behalf of future business Generated data Like network requests "
}
// Judge whether the data is correct Here is the wrong data use n2 Trigger
if (data.code == 404) {
n2(data.info) // Trigger
// After this program runs, the program will report an error
// except n2 Can trigger Promise Generate wrong data You can also throw errors directly
// throw " I am the wrong data in business "
} else if (data.code == 200) {
n1(data.info)
}
})
// The following code is no longer executed
p.then(function(data){
console.log(data)
}).catch(function(err){
console.log(404); //404
})
console.log(111) //111
</script>After catching the error , You can continue to perform the following .
So far we have learned Promise Basic use of , Then there is a special case , When the correct data is a new Error Type , Will the program report errors ?
Obviously, there will be no error , Because it is a correct business object , It's just a err Object of type .
Code display :
<script>
// Create a Peomise object
var p = new Promise(function(n1,n2){// there n1,n2 Is the callback function
var data = {
code: 200,
info: " Fake data On behalf of future business Generated data Like network requests "
}
// Judge whether the data is correct Here is the wrong data use n2 Trigger
if (data.code == 404) {
n2(data.info)
} else if (data.code == 200) {
var err=new Error(" The right business object But it's a js Medium err Object of type ")
n1(err)
}
})
p.then(function(data){
console.log(data) //Error: The right business object But it's a js Medium err Object of type
}).catch(function(err){
console.log(404);
})
</script>
边栏推荐
- 【英雄哥七月集训】第 26天:并查集
- [ACNOI2022]总差一步
- 分布式事务——Senta(一)
- P6118 [joi 2019 final] solution to the problem of Zhenzhou City
- Commissioning experience of ROS
- Typescript (zero) -- introduction, environment construction, first instance
- 使用PyTorch的TensorBoard-可视化深度学习指标 | PyTorch系列(二十五)
- 【红队】ATT&CK - 文件隐藏
- 【英雄哥七月集训】第 27天:图
- [brother hero's July training] day 26: check the collection
猜你喜欢

数据中台夯实数据基础
![[software testing] - unittest framework for automated testing](/img/7a/29b222cb0b6a5953b98f8d797cd106.png)
[software testing] - unittest framework for automated testing

Pycharm 快速给整页全部相同名称修改的快捷键

【TA-霜狼_may-《百人计划》】图形3.5 Early-z 和 Z-prepass

Actual case of ROS communication

Using pytorch's tensorboard visual deep learning indicators | pytorch series (25)
![[signal denoising] signal denoising based on Kalman filter with matlab code](/img/9e/9e569c83dc3106570cf7571056867f.png)
[signal denoising] signal denoising based on Kalman filter with matlab code

Redis aof日志持久化

Docker高级篇-Docker容器内Redis集群配置

Job 7.27 IO process
随机推荐
CNN training cycle reconstruction - hyperparametric test | pytorch series (XXVIII)
别再用 offset 和 limit 分页了,性能太差!
新基建助力智能化道路交通领域的转型发展
CNN循环训练的解释 | PyTorch系列(二十二)
Chapter III queue
[TA frost wolf \u may - hundred people plan] Figure 3.7 TP (d) r architecture of mobile terminal
NPDP考生!7月31号考试要求在这里看!
IO flow: node flow and processing flow are summarized in detail.
数据湖:数据库数据迁移工具Sqoop
“29岁,普通功能测试,我是如何在一周内拿到5份Offer的?”
unordered_ The hash function of map and the storage mode of hash bucket
openGauss源代码,用什么IDE工具管理、编辑、调试?
Day 19 of leetcode
MySQL is shown in the figure. The existing tables a and B need to be associated with a and B tables through projectcode to find idcardnum with different addresses.
How to simply realize the function of menu dragging and sorting
windbg
[self growth website collection]
Deep residual learning for image recognition shallow reading and Implementation
Newline required at end of file but not found.
[QNX Hypervisor 2.2用户手册]9.10 pass