当前位置:网站首页>Promise 在uniapp的简单使用
Promise 在uniapp的简单使用
2022-07-06 08:41:00 【菜鸟驿站2020】
Promise接受两个函数作为参数,由Javascript引擎提供,不用自己部署。
resolve 成功函数 | reject 失败函数
resolve(): 使当前Promise对象的状态改成fulfilled
reject(): 使当前Promise对象状态改成rejected
Promise状态的改变是一次性的,即执行了resolve函数后就不会执行reject函数了。
var n = 0
//实例化 promise
let promise = new Promise(function(resolve, reject) {
//需要耗时的任务,在本例中使用setTimeout(...)来模拟异步代码
setTimeout(function(){
if(n%2 === 0){
resolve(n)
n = n+1
}else{
reject(n%2)
n = n+1
}
}, 1000)
})
//调用实例的方法
promise.then(result =>{
//当Promise的状态是fulfilled时执行
console.log('成功'+ result)
}).catch(error =>{
//1. 当Promise的状态改为rejcted ,被执行
//2. 当Promise执行体出现错误时,被执行
console.log('失败'+ error)
}).finally(()=>{
console.log("成功-失败-都执行")
})
另一种是调用函数方式
click1() {
this.PR1().then(result => {
console.log('resolved成功回调')
console.log('成功回调接受的值:', result)
}).catch(error => {
console.log('catch失败执行回调抛出失败原因:', error)
})
},
PR1() {
let p = new Promise(function(resolve, reject) {
setTimeout(function() {
var num = Math.ceil(Math.random() * 20) //生成1-20的随机数
console.log('随机数生成的值:', num)
if (num <= 10) {
resolve(num)
} else {
reject('数字大于10了即将执行失败回调')
}
}, 1000)
})
return p
}
边栏推荐
- sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
- What is CSRF (Cross Site Request Forgery)?
- Tcp/ip protocol
- China dihydrolaurenol market forecast and investment strategy report (2022 Edition)
- China Light conveyor belt in-depth research and investment strategy report (2022 Edition)
- [MySQL] log
- MySQL learning records 12jdbc operation transactions
- Hutool gracefully parses URL links and obtains parameters
- 堆排序详解
- Visual implementation and inspection of visdom
猜你喜欢
2022 Inner Mongolia latest water conservancy and hydropower construction safety officer simulation examination questions and answers
704 二分查找
What is CSRF (Cross Site Request Forgery)?
Unified ordering background interface product description Chinese garbled
被破解毁掉的国产游戏之光
Restful API design specification
Precise query of tree tree
Leetcode question brushing (5.28) hash table
Roguelike游戏成破解重灾区,如何破局?
企微服务商平台收费接口对接教程
随机推荐
如何进行接口测试测?有哪些注意事项?保姆级解读
Trying to use is on a network resource that is unavailable
[NVIDIA development board] FAQ (updated from time to time)
根据csv文件某一列字符串中某个数字排序
torch建立的网络模型使用torchviz显示
2022.02.13 - NC004. Print number of loops
【ROS】usb_cam相机标定
MySQL learning record 10getting started with JDBC
PC easy to use essential software (used)
[MySQL] log
sys. argv
ROS compilation calls the third-party dynamic library (xxx.so)
Report on Market Research and investment prospects of China's silver powder industry (2022 Edition)
Shift Operators
Image,cv2读取图片的numpy数组的转换和尺寸resize变化
2022.02.13 - NC001. Reverse linked list
Mobile phones and computers on the same LAN access each other, IIS settings
What is CSRF (Cross Site Request Forgery)?
poi追加写EXCEL文件
Purpose of computer F1-F12