当前位置:网站首页>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
}

边栏推荐
- 查看局域网中电脑设备
- 2022.02.13 - NC004. Print number of loops
- 【Nvidia开发板】常见问题集 (不定时更新)
- [NVIDIA development board] FAQ (updated from time to time)
- Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
- Charging interface docking tutorial of enterprise and micro service provider platform
- C语言双指针——经典题型
- China's high purity aluminum target market status and investment forecast report (2022 Edition)
- Hutool gracefully parses URL links and obtains parameters
- Deep analysis of C language data storage in memory
猜你喜欢
随机推荐
【ROS】usb_ Cam camera calibration
Deep learning: derivation of shallow neural networks and deep neural networks
Precise query of tree tree
sublime text的编写程序时的Tab和空格缩进问题
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
【Nvidia开发板】常见问题集 (不定时更新)
POI add write excel file
Beijing invitation media
MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
Colorlog结合logging打印有颜色的日志
China dihydrolaurenol market forecast and investment strategy report (2022 Edition)
查看局域网中电脑设备
目标检测——Pytorch 利用mobilenet系列(v1,v2,v3)搭建yolov4目标检测平台
自动化测试框架有什么作用?上海专业第三方软件测试公司安利
Summary of MySQL index failure scenarios
[NVIDIA development board] FAQ (updated from time to time)
sys.argv
Visual implementation and inspection of visdom
Delay initialization and sealing classes
【ROS】usb_cam相机标定






![Verrouillage [MySQL]](/img/ce/9f8089da60d9b3a3f92a5e4eebfc13.png)


