Promise

几种状态

  • onFulfilled 执行状态,resolve()被调用
  • onRejected 拒绝状态,reject()被调用
  • pending 等待状态(进行中)

创建Promise

方式一:直接 new Promise

function asyncFun (arg) {
  return new Promise((resolve, reject) => {
    if (arg) {
      resolve('yes')
    } else {
      reject('no')
    }
  })
}

方式二:使用快捷方式创建

function asyncFun (arg) {
  if (arg) {
    return Promise.resolve('yes')
  } else {
    return Promise.reject('no')
  }
}

调用方式

普通调用

asyncFun(true).then(res => {
  console.log(res)
}).catch(e => {
  console.warn(e)
})

async..await

;(async () => {
  try {
    let ret = await asyncFun(true)
    console.log(ret)
  } catch (e) {
    console.warn(e)
  }
})();

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress