Promise对象使用

版权声明:干一行、爱一行、爱学习、爱分享! https://blog.csdn.net/weixin_36951197/article/details/84787346
  • Promise 简单例子1
    状态由等待变为(成功/resolve)或 (失败/reject),传的参数作为then函数中成功函数的实参
new Promise(function(resolve, reject) {
	//默认情况下是pending,如果状态先转变为成功就执行成功回调,否则执行失败回调。状态一旦改变了就不能再改变了。
	alert('start')
	//成功状态
	setTimeout(function(){ 
		resolve('success'); 
	}, 2000);
	//失败状态
	setTimeout(() => reject(new Error('fail')), 3000)
	
}).then(function(val) {//成功状态的回调
  alert(val);
},function(e) {//失败状态的回调
  alert(e);
});

alert('Hi!');
  • Promise 简单例子2
    .then是链式调用 依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数,不加return 的话,第二个.then的result为 undefined。
const p1 = new Promise(function (resolve, reject) {
  setTimeout(() => resolve('success'),3000)
	setTimeout(() => reject('请求超时!'),5000)
})

const p2 = new Promise(function (resolve, reject) {
 resolve(p1)		
})

p2
  .then(result => {
	  alert(result)
	  return result
  })
  //.then是链式调用 依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
  .then(result => alert('第二个then-'+result))//第二个then-success
  .then(result => alert('第三个then-'+result)) //第三个then-undefined
  .catch(error => alert(error))
  
  • Promise.all()的用法
    Promise.all方法执行后返回的依旧是promise, all两个全成功才执行 。
    如果有一个函数执行了reject,就回被catch捕捉。
function show(s) {
   return new Promise(function (resolve, reject) {
	 if(s>7){
		reject('err')
	}
	setTimeout(function () {
	    resolve(s)
	 }, s*1000)
  })
}

let result = Promise.all([show(3), show(6)]);
result.then((data) => {
    console.log(data) // 6秒后输出 [ 3, 6 ]  
})
.catch(error => alert(error))
  • Promise.race的用法
    如果先成功了那就成功了, 如果先失败了那就失败了
function show(s) {
   return new Promise(function (resolve, reject) {
    setTimeout(function () {
         resolve(s)
     }, s*1000)	
	if(s>5){			
		setTimeout(function () {
				reject(s)
		}, s*1000)					
	}
   })
}

let result = Promise.race([show(3), show(4),show(6)]);
result.then((data) => {
   console.log(data) //3
})
.catch(error => alert(error))

猜你喜欢

转载自blog.csdn.net/weixin_36951197/article/details/84787346