@15013890200
2018-09-25T10:41:06.000000Z
字数 1419
阅读 528
javascript
promise
setTimeout
- 由于javascript的语言特性,即所用代码的执行都是单线程的,所有涉及到的网络操作、浏览器事件都必须是异步的。
- 利用Promise,可以将和某一请求事件相关的操作定义到一个执行链上,这样做的优点:先统一执行ajax请求,不必关心如何处理结果。然后根据请求的结果,在将来的某个时间调用resolve或者reject函数
- 同时,也学到了如何向setTimeout的回调函数传参数。即
setTimeout(回调函数,毫秒数,参数1,参数2,...)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>promise</title>
</head>
<body>
<script type="text/javascript">
'use strict';
var num = 10086;
function ajaxFunc(resolve,reject){
let timeOut = Math.random()*2;
console.log('开始执行ajaxFunc啦');
setTimeout(function(){
if(timeOut > 1){
console.log('函数执行成功');
let ret = {
code: 0,
msg: 'timeOut: ' + timeOut
}
num = 10000;
resolve(ret);
}
else{
console.log('函数执行失败');
reject('timeOut: ' + timeOut);
}
},timeOut*1000);
}
// var pro = new Promise(ajaxFunc).then(function(res){
// console.log(res);
// success();
// }).catch(function(res){
// console.log(res);
// });
// function success(){
// console.log('num = ' + num);
// }
function multiple(num){
return new Promise(function(resolve,reject){
console.log('this function is '+ num + ' * ' + num);
if(num > 10000){
reject('num is too large');
}
setTimeout(resolve,1000,num*num);
});
}
function add(num){
return new Promise(function(resolve,reject){
console.log('this function is ' + num + ' + ' + num);
setTimeout(resolve,1000,num+num)
})
}
var p1 = new Promise(function(resolve,reject){
console.log('start calculate ');
resolve(345);
});
p1.then(multiple)
.then(multiple)
.then(add)
.then(function(result){
console.log('value is ' + result);
})
.catch(function(res){
console.log(res);
})
</script>
</body>
</html>