浅谈promise(起码看完让你会用它的then、catch、resolve、reject、race等方法)

来源:互联网 发布:指南针软件 股票 编辑:程序博客网 时间:2024/04/30 11:16

抽象异步处理对象以及对其进行各种操作的组件

主要类型

  • Constructor 构造函数
  • Instance Method 实例方法
  • Static Method 静态方法

**promise.then(onFulfilled, onRejected)操作之后执行回调函数。**Fulfilled为执行成功调用的函数,onRejected为执行失败调用的函数。

promise.catch(onRejected)捕获到错误执行onRejected函数

promise状态

  • 只能由pending到fulfilled或Rejected
  • 状态不可逆
graph LRPending-->Fulfilled Pending-->Rejected
  1. 使用new Promise方法创建promise对象。
  2. .then.then添加promise对象的处理函数。

Promise.resolve/Promise.reject

静态方法Promise.resolve(value) 可以认为是 new Promise() 方法的快捷方式。

new Promise(function(resolve){    resolve(42);});

promise的链式写法(chain)

function taskA() {    console.log("Task A");}function taskB() {    console.log("Task B");}function onRejected(error) {    console.log("Catch Error: A or B", error);}function finalTask() {    console.log("Final Task");}var promise = Promise.resolve();promise    .then(taskA)    .then(taskB)    .catch(onRejected)    .then(finalTask);

对应流程图

  • then 注册onFulfilled时的回调函数
  • catch 注册onRejected时的回调函数

链式写法的参数传递

function doubleUp(value) {    return value * 2;}function increment(value) {    return value + 1;}function output(value) {    console.log(value);// => (1 + 1) * 2}var promise = Promise.resolve(1);promise    .then(increment)    .then(doubleUp)    .then(output)    .catch(function(error){        // promise chain中出现异常的时候会被调用        console.error(error);    });

参数传递流程图

promise.all

Promise.all 接收一个 promise对象的数组作为参数,当这个数组里的所有promise对象全部变为resolve或reject状态的时候,它才会去调用 .then 方法。

Promise.all([request.comment(), request.people()]);
  • request.comment()request.people()会同时执行(并行执行)。
  • promise的结果和传递给Promise.all的数组的顺序一致。

promise.race

Promise.race只要有一个promise对象进入 FulFilled 或者 Rejected 状态的话,就会继续进行后面的处理。

注:promise.race在第一个函数执行完毕后,并不会取消其他函数的执行状态,但是其余函数执行完毕之后不会再调用.then

then与catch

.catch 也可以理解为 promise.then(undefined, onRejected),但实际使用中我们还是会将then与catch分开使用。

function throwError(value) {    // 抛出异常    throw new Error(value);}// <1> onRejected不会被调用function badMain(onRejected) {    return Promise.resolve(42).then(throwError, onRejected);}// <2> 有异常发生时onRejected会被调用function goodMain(onRejected) {    return Promise.resolve(42).then(throwError).catch(onRejected);}// 运行示例badMain(function(){    console.log("BAD");});goodMain(function(){    console.log("GOOD");});//输出结果`GOOD`
  • 使用.then即使 throwError 抛出了异常,onRejected 指定的函数也不会被调用。
  • 使用.catch因为是链式操作,会捕获到上一步.then中抛出的操作。

END

阅读全文
0 0
原创粉丝点击