美文网首页
Promise 链式调用

Promise 链式调用

作者: sunshineLWZL | 来源:发表于2019-07-26 17:48 被阅读0次

Promise

  • status
    状态,有三种状态pendding、resolved、rejected,状态由 pending->resolved/rejected,不可逆
  • resolve
    resolve 方法,修改 promise 的状态为 resolved,执行 resolve 回调
  • reject
    reject 方法,修改 promise 的状态为 rejected,并执行 reject 的回调
  • then
    用于 promise 链式调用,返回一个新的 Promise 对象

常规使用方法

 const p = new Promise((resolve, reject) => {
    // 执行一堆操作
    resolve() // reject()
})
p.then(res => {
  // 成功回调函数
}, err => {
  // 失败回调函数
})
p.then(() => {}, () => {})
// then 方法会将成功回掉函数添加到 Promise 的成功回调队列,将失败回调函数添加到失败回调队列,一个 promise 对象可以调用多次 then 方法,并返回一个新的 Promise 对象,所以可以进行链式调用

链式调用

const p1 = new Promise((resolve, reject) => {
  resolve(1)
})
const p2 = new Promise((resolve, reject) => {
  resolve(2)
})
p1.then(res => { // 第一次调用 then
  console.log(res) // 1
  return p2
}).then(res => { // 第二次调用 then
  console.log(res) // 2
})
// 思考, 为什么 第二次调用 then 里面的成功回调函数的参数值会是p2的 resolve的值?
// then返回值具体规则
/* 
- 如果返回一个值,则 then 返回的 Promise 状态成为 resolved,并且返回的值作为回调的参数值
- 若没有返回值,则状态为 resolved,参数值为 undefined
- 若回调函数抛出错误,则为 rejected,抛出的错误为拒绝状态的参数值
- 若返回 promise 对象,则状态与该 promise 状态一致,并且回调函数的参数值为该 promise 的状态参数值。
*/  
p1.then(res => {
  return 'return value'
}).then (res => {
  console.log(res) // 'return value'
}).then(res => {
   console.log(res) // undefined
   return p2
}).then(res => {
  console.log(res) // 2
  console.log(undefined.name)
}, err => {
  console.log(err) //不会执行
})
.then(res => {}, err => {
  console.log(err) // TypeError: Cannot read property 'name' of undefined
  return 'err'
})
.catch(err => {
  console.log(err) // 不会执行
})
.then(res => {
  console.log(res) // 'err'
  console.log(undefined.name)
})
.then(res => {
  console.log(res) // 不会执行
})
.catch(err => {
  console.log(err) //  TypeError: Cannot read property 'name' of undefined
})

// 关于promise catch 的执行,传递到最近一次的 catch 方法,

相关文章

  • js promise图解

    链式调用 封闭promise

  • 嵌套的promise执行顺序

    外部promise有多个then链式调用,第一个then里面执行另一个promise,也带多个then链式调用,他...

  • Promise链式调用

    做了一个博客项目,有一个过程如下: 封装request函数(用axios发送请求),axios会返回一个promi...

  • Promise链式调用

    一、Promise对象 承诺一定会实现,更简单的处理异步请求。同时更加方便使用链式调用。缺点:Promise对象状...

  • Promise 链式调用

    Promise status状态,有三种状态pendding、resolved、rejected,状态由 pend...

  • ES6

    AJAX 异步网络请求 Promise 使用了Promise对象之后可以链式调用的方式组织代码 Promise.a...

  • 手写Promise

    1. 简易版Promise,只能调用一次then,不能链式调用:

  • Promise用法详解

    参考promise|深入理解 promise:promise的三种状态与链式调用 Promise对象只有三种状态 ...

  • async和await

    promise链 原来用promise的链式调用方式,then 中原本就返回了一个promise async 函数...

  • 八(2)Promise模拟(姜) ------ 2020-05-

    1、基础的Promise的实现 2、实现then的链式调用

网友评论

      本文标题:Promise 链式调用

      本文链接:https://www.haomeiwen.com/subject/dcedrctx.html