pomise的简单用法
2024-08-30 09:07:35
1、then的基本简单用法,当异步获取完数据后就会自动执行then的方法
function runAsync1(){
var p = new Promise(function(resolve, reject){
//做一些异步操作
setTimeout(function(){
console.log('执行完成');
resolve('随便什么数据');
}, 3000);
});
return p;
} renAsync1().then(function(data){
console.log(data);//随便什么数据
})
2、then的链式基本用法,一个一个触发
runAsync1().then(function(data){
console.log(data);//随便什么数据1
return runAsync2();
}).then(function(data){
console.log(data);//随便什么数据2
})
3、提供两种数据传递方式resolve(),和reject()(注意两者一次只能触发其一)
function getNumber(){
var p = new Promise(function(resolve, reject){
//做一些异步操作
setTimeout(function(){
var num = Math.ceil(Math.random()*10); //生成1-10的随机数
if(num<=5){
resolve(num);
}
else{
reject('数字太大了');
}
}, 2000);
});
return p;
} getNumber()
.then(
function(data){
console.log('resolved');
console.log(data);
},
function(reason, data){
console.log('rejected');
console.log(reason);
}
);
4、当发生错误时触发的catch
getNumber()
.then(function(data){
console.log('resolved');
console.log(data);
console.log(somedata); //此处的somedata未定义
})
.catch(function(reason){
console.log('rejected');
console.log(reason);
});
5、全部同时执行的all(全部执行完成才输出数据,且数据也是数组格式)
Promise
.all([runAsync1(), runAsync2(), runAsync3()])
.then(function(results){
console.log(results);
});
6、谁快先执行谁的race
Promise
.race([runAsync1(), runAsync2(), runAsync3()])
.then(function(results){
console.log(results);
});
最新文章
- Razor 语法初级使用,不断更新此文章
- Search Insert Position
- 【POJ】2420 A Star not a Tree?
- Apache CXF 101 Win Eclipse开发环境搭建
- [CSS]如何正确使用ID和Class?
- 开源图形库 c语言-图形图像库 集合[转]
- SQL经典笔试题之一
- SPOJ LIS2 Another Longest Increasing Subsequence Problem 三维偏序最长链 CDQ分治
- Linux 安全
- java开发网易电话面试 一面总结
- 庞玉栋:浅谈seo优化对于网站建设的重要性
- 好用的SQLAlchemy
- EBS系统克隆
- 微信小程序是怎么运行的?
- Java的IO流——(七)
- JSON.parseObject 和 JSON.toJSONString
- golang 打印变量类型
- Rails NameError uninitialized constant class solution
- 内核诊断(1)interrupt took too long
- SharePoint Tricks - HTML &; CSS &; JavaScript
热门文章
- bzoj 1876 高精
- laravel 获得各个根文件夹路径的方法及路由的一些使用
- python基础===map和zip的用法
- 使用pandas进行数据清洗
- vs附加到进程报MSVSMON.EXE未在远程计算机启动错误
- delphi string,pchar,char的比较
- SQLAlchemy技术文档(中文版)-下
- 服务器老是出现502 Bad Gateway?
- C# 连接SQL数据库以及操作数据库
- [/wp_active.php]