Promise

promise 是 es6 提出,处理异步流程的语法,用来代替旧的异步回调函数
执行器 excutor Promise(excutor)
Promise.prototype.then()

const pro1 = new Promise( (resolve, reject) => { // 同步回调函数,即 new Promise 的时候就执行,触发内部异步代码执行
  setTimeout( () => { resolve() }, 0)
})

pro1.then( res => { // 异步回调函数,当 promise 内部的状态有变化时候触发
  doSomeThingSync()
})

回调地狱:
n 个串行的异步操作,旧的回调函数写法必须在第一个内的 success 回调内执行第二个回调操作,形成回调地狱

function asyncfn(options, success, error) {
  
}

promise 支持链式调用,可以较好的解决回调地狱(不是最好的,还是需要写回调函数)

dosomePromise()
  .then(res => doOtherPromise(res))
  .then( newRes => doLastPromise(newRes))
  .catch( error => {} )

配合 es7 async/await 语法(目前回调函数终极解决方案)

// 纯粹的同步方式 从上写到下没有回调函数,保证代码执行顺序
async function fn() {
  try {
    const res = await dosomePromise();
    const newRes = await doOtherPromise();
    const finallyRes = await doLastPromise();
  } catch (error) {
    handleError(error)
  }
}

Promise 最厉害的地方在于,
以前的异步回调函数必须在异步代码执行前显示的指定成功的回调函数和失败的回调函数
而 Promise 一旦定义后,内部的状态在任何时候都可以被获取到,即异步代码直接完毕后还可以获取状态

const pro1 = new Promise( (reslove, reject) => {
  setTimeout(() => {
    reslove( 'done' )
  }, 1000)
})

setTimeout( () => {
  pro1.then( res => { console.log(res) })
}, 5000)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值