Promise链式调用(es6异步调用then结构)

promise俗称链式调用,它是es6中最重要的特性之一
简单的说可以不停的then调用嵌套在调用(异步之后,链式调用方式执行回调),这种操作方式称为promise

/*包含两个参数:resolve,reject;
Resolve:将promise的状态设置为完成状态(resolved),此时then方法捕捉变化,执行成功的回调
Reject:将promise状态设置为无效,(rejected),此时then方法执行失败回调*/
var fun1=function(){
       var p=new Promise(function(resolve,reject){
	             setTimeout(function (){
	                       console.log("我是fun1")
				 resolve("fun1T")
		         },1000)
	  })
	 return p;
}		

var fun2= function(param1){
	console.log("参数->"+(param1?param1:''));
    console.log('我是fun2');
    var p=new Promise(function(resolve,reject){
             setTimeout(function (){
	               resolve('fun2T');
              },2000)
	})
	return p;
}
			
//结合then来链式调用
/*var fun2T=fun2().then(function(param){
		console.log(param)
})
var fun1T=fun1().then(function(param){
		console.log(param)
})*/

/*
控制台:
参数->
我是fun2
我是fun1
fun1T
fun2T
*/

//then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。
/*fun1()
.then(data=>{
	return fun2(data);
})
.then((data)=>{
	console.log(data)
})*/
//上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。

/*
控制台:
我是fun1
参数->fun1T
我是fun2
fun2T
*/

//Promise之All,等执行所有异步,完事之后执行then回调返回出数组数据类型
Promise.all([fun1(),fun2()]).then(function(data){console.log(data)})
/*
控制台:
参数->
我是fun2
我是fun1
["fun1T", "fun2T"]
*/

猜你喜欢

转载自blog.csdn.net/lwang_IT/article/details/88072662