关于javascript:Promise基础消化错误和抛出错误

41次阅读

共计 2222 个字符,预计需要花费 6 分钟才能阅读完成。

then

then 函数的会接管两个回调函数,一个是 onFulfilled 函数,一个是 onRejected 函数

如果这两个回调函数没有写返回值,默认会 return undefined;

进入下一个函数的 onFulfilled 函数中

const p = new Promise((resolve, reject) => {resolve(22);
});
p.then((success1) => {console.log("success1", success1); // "success2" 22
    // 没写 return 默认返回 return undefined
  },
  (err1) => {console.log("err1", err1);
  }
).then((success2) => {console.log("success2", success2); // "success2" undefined
  },
  (err2) => {console.log("err2", err2);
  }
);

在这两个回调中 return xxx,相当于调用 return new Promise((resolve) => resolve(xxx));

const p = new Promise((resolve, reject) => {resolve(22);
});
p.then((success1) => {return new Promise((resolve, reject) => resolve("success"));
    // 等价于
    return "success";
  },
  (err1) => {console.log("err1", err1);
  }
).then((success2) => {console.log("success2", success2); // "success2" "success"
  },
  (err2) => {console.log("err2", err2);
  }
);

onFulfilled 函数和 onRejected 函数中默认返回的都是胜利,如果须要返回失败须要显示调用 reject 或者用 throw 抛出谬误能够

const p = new Promise((resolve, reject) => {resolve(22);
});
p.then((success1) => {return new Promise((resolve, reject) => reject("error"));
    // 等价于
    // throw "error";
  },
  (err1) => {console.log("err1", err1);
  }
).then((success2) => {console.log("success2", success2);
  },
  (err2) => {console.log("err2", err2); // "err2" error
  }
);

总结:在 then 回调中 return xxx 会被主动包装成 return new Promise((resolve) => resolve(xxx));

catch

catch 是用来解决 rejected 状态,是 then 函数的一种特例,相当于 then(null, (err) => {});

catch 为什么能捕捉后面的谬误?

onRejected 函数中,如果没有显示抛出谬误,默认会 return undefined; 进入一下个 onFulfilled 函数

finally

finally 不论以后 promise 是什么状态都会执行,也是 then 函数的一种特例,相当于 `then(result => result, err => new Promsie((\_, reject) => reject(err)));

Promise.resolve

Promise.resolvePromisefulfilled 状态时的简写,相当于 new Promise(resolve => resolve(xxx))

onFulfilled 函数接管参数

  • 当参数是一般参数时,会间接传递给前面 then 函数

    new Promise((resolve) => resolve({name: "uccs"})).then((data) => {console.log(data);
    });
  • 当参数是 Promise 对象时,前面的 then 会依据传递的 Promise 对象的状态变动执行哪一个回调

    const p = new Promise((resolve, reject) => {setTimeout(resolve, 1000, "我执行了");
    });
    new Promise((resolve) => resolve(p)).then((data) => {console.log(data);
    });
  • 具备 then 办法的对象

    • 用这种这种形式,如果须要扭转 Promise 状态是,不能应用 return 模式,这个 then 办法也是有两个回调函数的:onFulfilledonRejected

      const thenable = {then(resolve, reject) {console.log("thenable");
      },
      };
      new Promise((resolve) => resolve(thenable)).then((data) => {console.log(data);
      });

Promise.reject

Promise.rejectPromiserejected 状态是的简写,相当于 new Promise((_, reject) => reject(xxx))

onRejected 函数不论接管什么参数,都会一成不变的向后传递,作为后续办法的参数

正文完
 0