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)