ES6中的Promise对象如何使用

本文小编为大家详细介绍“ES6中的Promise对象如何使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“ES6中的Promise对象如何使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

我们提供的服务有:成都网站设计、网站制作、微信公众号开发、网站优化、网站认证、平坝ssl等。为成百上千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的平坝网站制作公司

在promise之前处理异步回调的方式

function asyncFun(a,b,callback) {
   setTimeout(function () {
    callback(a+b);
   },200);
  }
  asyncFun(1,2, function (res) {
   if(res > 2) {
    asyncFun(res, 2, function (res) {
     if(res > 4) {
      asyncFun(res, 2, function (res) {
       console.log('ok');
       console.log(res);
      })
     }
    })
   }
  });

从上面可以看出所谓的”回调地狱”的可怕

使用promise来优雅的处理异步

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 console.log('ok');
 console.log(res);
})
.catch(function (error) {
 console.log(error);
});

使用promise处理内部异常的举例

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  // 模拟异常判断
  if(typeof a !== 'number' || typeof b !== 'number') {
   reject(new Error('no number'));
  }
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
},function (err) {
 console.log('first err: ', err);
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 'a');
 }
},function (err) {
 console.log('second err: ', err);
})
.then(function (res) {
 console.log('ok');
 console.log(res);
},function (err) {
 console.log('third err: ', err);
});

从上面可以看出通过then的第二个回调函数处理promise对象中的异常,通过reject返回异常的promise对象

通过catch统一处理错误,通过finally执行最终必须执行的逻辑

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  // 模拟异常判断
  if(typeof a !== 'number' || typeof b !== 'number') {
   reject(new Error('no number'));
  }
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
asyncFun(1,2)
.then(function (res) {
 if(res > 2) {
  return asyncFun(res, 2);
 }
})
.then(function (res) {
 if(res > 4) {
  return asyncFun(res, 'a');
 }
})
.then(function (res) {
 console.log('ok');
 console.log(res);
})
.catch(function (error) {
 console.log('catch: ', error);
})
.finally(function () {
 console.log('finally: ', 1+2);
});

通过Promise.all()静态方法来处理多个异步

function asyncFun(a,b) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },200);
 })
}
var promise = Promise.all([asyncFun(1,2), asyncFun(2,3), asyncFun(3,4)])
promise.then(function (res) {
 console.log(res); // [3, 5, 7]
});

通过Promise.race()静态方法来获取多个异步中最快的一个

function asyncFun(a,b,time) {
 return new Promise(function (resolve, reject) {
  setTimeout(function() {
   resolve(a + b);
  },time);
 })
}
var promise = Promise.race([asyncFun(1,2,10), asyncFun(2,3,6), asyncFun(3,4,200)])
promise.then(function (res) {
 console.log(res); // 5
});

通过Promise.resolve() 静态方法来直接返回成功的异步对象

var p = Promise.resolve('hello');
p.then(function (res) {
 console.log(res); // hello
});

等同于,如下:

var p = new Promise(function (resolve, reject) {
 resolve('hello2');
})
p.then(function (res) {
 console.log(res); // hello2
});

通过Promise.reject() 静态方法来直接返回失败的异步对象

var p = Promise.reject('err')
p.then(null, function (res) {
 console.log(res); // err
});

等同于,如下:

var p = new Promise(function (resolve, reject) {
 reject('err2');
})
p.then(null, function (res) {
 console.log(res); // err
});

通过一个小例子来测试Promise在面向对象中应用

'use strict';
class User{
 constructor(name, password) {
  this.name = name;
  this.password = password;
 }
 send() {
  let name = this.name;
  return new Promise(function (resolve, reject) {
   setTimeout(function () {
    if(name === 'leo') {
     resolve('send success');
    }else{
     reject('send error');
    }
   });
  });
 }
 validatePwd() {
  let pwd = this.password;
  return new Promise(function (resolve, reject) {
   setTimeout(function () {
    if(pwd === '123') {
     resolve('validatePwd success');
    }else{
     reject('validatePwd error');
    }
   });
  })
 }
}
let user1 = new User('Joh');
user1.send()
 .then(function (res) {
  console.log(res);
 })
 .catch(function (err) {
  console.log(err);
 });
let user2 = new User('leo');
user2.send()
 .then(function (res) {
  console.log(res);
 })
 .catch(function (err) {
  console.log(err);
 });
let user3 = new User('leo', '123');
user3.validatePwd()
 .then(function (res) {
  return user3.validatePwd();
 })
 .then(function (res) {
  console.log(res);
 })
 .catch(function(error) {
  console.log(error);
 });
let user4 = new User('leo', '1234');
user4.validatePwd()
 .then(function (res) {
  return user4.validatePwd();
 })
 .then(function (res) {
  console.log(res);
 })
 .catch(function(error) {
  console.log(error);
 });

读到这里,这篇“ES6中的Promise对象如何使用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。


网页名称:ES6中的Promise对象如何使用
分享链接:http://bzwzjz.com/article/gihhsj.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 网站建设 网站建设方案 网站建设开发 定制网站制作 成都网站设计 营销型网站建设 成都网站制作 成都网站设计 企业网站设计 高端网站设计推广 手机网站制作 温江网站设计 成都网站制作 网站制作 重庆企业网站建设 移动网站建设 定制网站建设多少钱 成都网站建设 成都网站建设 成都网站建设公司 成都营销网站建设 企业网站建设