j_promise

Promise 是一个构造函数

resolve 成功 / reject 失败

	//Promise 承若 无法改变的 // 做一件事 中间不能别打断 事情做完了会说(可能成功,可能失败,但都是做完了) 
	
	//Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。
	// 做一件事pending(进行中) resolve函数的作用把事情变为成功    reject函数的作用是把事情变为失败
	
	let pp=new Promise(function(resolve,reject){
		if(2 < 1){
			resolve("a");//成功  向外传出参数a
		}else{
			reject("b");//失败  向外传出参数b 
			console.log("执行完reject,还有没有执行下面的语句");//   返回 reject没有 return的行为 后面的代码依旧会执行
		}
	});		
	

Promise实例的then()方法

//pp.then()   then 之后,接着    (Promise这件事做完之后接着做的事,分成果和失败两种)
//第一关参数成功时做的函数
//第二个参数 失败时做的函数

pp.then(function(value){
	//成功时  
	//参数 value   resolve传过来的 
	console.log(value);  //a
},function(e){
	//成功时       
	//参数 e   reject传过来的
	console.log(e); //b
	
})
	

promise 栗子

	//一般的使用都是 函数返回一个promise
	
	function isNumber(nn){
		let p=new Promise(function(resolve,reject){
			if(typeof nn == typeof 1){
				resolve("是数字");
			}else{
				reject("不是");
			}
		})
		return p;
	}
	isNumber(2).then(function(a){  //这样就可以直接 .then了
		console.log(a);  //是数字
	},function(b){
		console.log(b);  //是数字
	})
	

链式 then(), 一般用 在 上一个执行完才执行下一个

//使用new Promise(fn)或者它的快捷方式Promise.resolve()、Promise.reject(),返回一个promise对象

//then() 方法返回一个promise 实例(跟原来的不一样了,所以then()后面可以跟then)
//   上一个then的return 
Promise.resolve().then(function(){
	return "123"
}).then(function(a){
	console.log(a);//123   上一个的return 就是下一个的参数
	return "456";
}).then(function(b){
	console.log(b);//456
})		
	
Promise.resolve().then(function(){
	setTimeout(function(){
		return "123"
	},1000);
}).then(function(a){
	console.log(a);//unedefined     每一个都是按顺序执行的并不是等到上一个return执行完 才执行下一个
	return "456";
}).then(function(b){
	console.log(b);//456
})	
	

//似乎这才是正确的姿势
Promise.resolve().then(function(){
	let p1=new Promise(function(resolve,reject){
		setTimeout(function(){
			return resolve("123")
		},1000);
	});
	return p1;
	
}).then(function(a){
	console.log(a);//123 一秒以后才出现123
	return "456";
	
}).then(function(b){
	console.log(b);//456  
	
}).catch(function(error) {
  // 处理前面三个Promise产生的错误    catch方法的回调函数就是  then的第二个回调函数
}).finally(function(a){ //成果或失败都执行
	//不接受任何参数,因为不管你成功或失败都要执行 也就不管你返回什么了
	console.log(a+"哈哈哈");  //undefined哈哈哈
});
	
Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))		
	

猜你喜欢

转载自www.cnblogs.com/myniu/p/11783245.html
今日推荐