Promise是JS进行异步编程的新的解决方案(旧的是纯回调)
语法上:Promise是一个构造函数
功能上:Promise对象用来封装一个异步操作并可以获得其结果
Promise的状态改变
成功:pending变为resolved,失败:pending变为rejected
只有这两种,且一个promise对象只能改变一次
无论成功还是失败,都会有一个结果数据
成功的结构数据一般称为vlaue,失败的结果数据一般称为 reason
Promise的基本流程

new Promise( ) -> 执行异步操作
①成功:执行 resolve() -> Promise对象(resolved状态)-> 回调 onResolved( ) then() 新的Promise对象
②失败:执行reject( ) -> Promise对象(rejected状态) -> 回调onRejected then() / catch() 新的Promise对象
//1,创建一个新的promise对象
const p = new Promise((resolve,reject)=>{ //执行器函数是同步回调!
console.log(‘执行excutor‘); //立刻执行
//2,执行异步操作
setTimeout(()=>{
const time = Date.now()
if(time%2===0){
resolve(‘成功的数据,time=‘+time); //3.1 如果成功了, 调用 resolve(value)
}
else{
reject(‘失败的数据,time=‘+time); //3.2 如果失败了, 调用 reject(reason)
}
},1000)
console.log(‘123‘); //先输出执行 excutor
})
p.then(
value=>{ //接收成功得到的value onResolved(当成功的时候)
console.log(‘成功的回调:‘,value)
},
reason=>{ //接收失败得到的reason onRejected
console.log(‘失败的回调:‘,reason)
}
)
p.catch(
reason=>{
console.log(‘p.catch:‘,reason); // 接收得到失败的reason数据 onRejected 回调执行
}
)
//执行excutor
//123
//成功的回调: 成功的数据,time=1590557706934 / 失败的回调: 失败的数据,time=1590557756329
原文:https://www.cnblogs.com/shanlu0000/p/12972686.html