Promise

2018-09-19  本文已影响4人  igor_d140

原文链接: MDN

Promise
状态 pending, fulfilled, rejected
作用 代理对象(值),解决异步回调
特点 链式调用,成功(onfulfilled)和失败(onrejected)绑定相应处理方法
方法 优、缺点
Promise.all(iterable) 处理异步队列成功会返回一个promise对象(值为数组,顺序与队列一致)。队列中任一task出错将触发promise失败,仅返回出错task的错误信息
Promise.race(iterable) 返回最早返回值的task信息(不论成功失败)
Promise.reject(reason)
    let successQuery = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('successQuery')
        }, 1000)
      })
    }
    let errorQuery = () => {
      return new Promise((resolve, reject) => {
          reject('errorQuery')
      })
    }
    Promise.all([successQuery(), errorQuery()]).then(data => {
      console.log('success: ', data)
    }).catch(error => {
      console.log('error: ', error)
    })
    //error:  errorQuery

    //Promise.race(iterable)
    //@(1)
     let successQuery = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('successQuery')
        }, 3000)
      })
    }
    let errorQuery = () => {
      return new Promise((resolve, reject) => {
          setTimeout(() => {
          reject('errorQuery')
        }, 2000)
      })
    }
    Promise.race([successQuery(), errorQuery()]).then(data => {
      console.log('success: ', data)
    }).catch(error => {
      console.log('error: ', error)
    })
    // error:  errorQuery

    //@(2)
    let successQuery = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('successQuery')
        }, 1000)
      })
    }
    let errorQuery = () => {
      return new Promise((resolve, reject) => {
          setTimeout(() => {
          reject('errorQuery')
        }, 2000)
      })
    }
    Promise.race([successQuery(), errorQuery()]).then(data => {
      console.log('success: ', data)
    }).catch(error => {
      console.log('error: ', error)
    })
    // success:  successQuery
上一篇下一篇

猜你喜欢

热点阅读