当前位置:网站首页>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
}
边栏推荐
- Swagger setting field required is mandatory
- Deep learning: derivation of shallow neural networks and deep neural networks
- MySQL learning records 12jdbc operation transactions
- 704 二分查找
- ROS compilation calls the third-party dynamic library (xxx.so)
- Cisp-pte practice explanation
- Let the bullets fly for a while
- 软件压力测试常见流程有哪些?专业出具软件测试报告公司分享
- LDAP application (4) Jenkins access
- Restful API design specification
猜你喜欢
Hungry for 4 years + Ali for 2 years: some conclusions and Thoughts on the road of research and development
Tcp/ip protocol
延迟初始化和密封类
visdom可视化实现与检查介绍
ROS compilation calls the third-party dynamic library (xxx.so)
根据csv文件某一列字符串中某个数字排序
MySQL learning records 12jdbc operation transactions
CISP-PTE实操练习讲解
MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
Charging interface docking tutorial of enterprise and micro service provider platform
随机推荐
2022.02.13 - NC001. Reverse linked list
Colorlog结合logging打印有颜色的日志
Cisp-pte practice explanation
生成器参数传入参数
pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof
sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
[MySQL] lock
C語言雙指針——經典題型
Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges
Precise query of tree tree
The network model established by torch is displayed by torch viz
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
MySQL learning records 12jdbc operation transactions
电脑清理,删除的系统文件
【ROS】usb_ Cam camera calibration
延迟初始化和密封类
torch建立的网络模型使用torchviz显示
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
个人电脑好用必备软件(使用过)
【ROS】usb_cam相机标定