文章目录
Promise是JS中进行异步编程的新的解决方案
(旧的是纯回调)
- 语法上: Promise是一个构造函数
- 功能上: Promise对象用来封装一个异步操作并可以获得其结果
Promise状态
pending变为resolved;pending变为rejected
说明:
- 只有这两种状态,且一个promise对象只能改变一次
- 无论变为成功还是失败,都会有一个结果数据
- 成功的结果数据一般称为value,失败的结果数据一般称为reason
- 成功:resolved 失败:rejected
new Promise( function(resolve, reject) {…} /* executor */ );
executor是带有 resolve 和 reject 两个参数的函数 。 Promise构造函数执行时立即调用executor 函数,
resolve 和 reject 两个函数作为参数传递给executor(executor
函数在Promise构造函数返回所建promise实例对象前被调用)。 resolve 和 reject
函数被调用时,分别将promise的状态改为fulfilled(完成)或rejected(失败)。executor
内部通常会执行一些异步操作,一旦异步操作执行完毕(可能成功/失败),要么调用resolve函数来将promise状态改成fulfilled,要么调用reject
函数将promise的状态改为rejected。如果在executor函数中抛出一个错误,那么该promise
状态为rejected。executor函数的返回值被忽略。
Promise基本使用
//1.创建一个新的promise对象--传入的参数是一个回调函数,也就是定义中所说的执行器函数
//尽量使用const变量
const p = new Promise((resolve, reject) => {
//执行器函数是同步回调!!!
console.log('执行 excutor') //是会立刻执行的
//2.执行异步操作
setTimeout(() => {
const time = Date.now()//如果当前时间是偶数就代表成功,否则代表失败
//3.1 如果成功了,调用resolve(value)
if( time % 2 === 0 ){
resolve('成功的数据,time=' + time)
} else {
//3.2 如果失败,调用reject(reason)
reject('失败的数据,time=' + time)
}
}, 1000)
})
console.log('new Promise()之后') //先输出执行 excutor
// then()指定成功或失败的回调函数
p.then(
value => {
//接收得到成功的value数据 onResolved: 当变为resolved时执行
console.log('成功的回调', value)
},
reason => {
//接收失败得到的reason onRejected
console.log('失败的回调', reason)
}
)
执行 excutor
new Promise()之后
失败的回调 失败的数据,time=1586181072611 //promise定义时,reject(reason)
对比不同回调方式
- 指定回调方式更加灵活
- 旧的: 必须在启动异步任务前指定
- promise:启动异步任务=>返回promise对象 =>给promise对象绑定回调函数(甚至可以在异步任务结束之后指定)
异步任务可以先进行,我可以3s之后再来取结果,也就是我需要的时候去拿
- 支持链式调用, 解决回调地狱
- 回调地狱:回调函数嵌套套用,外部回调函数异步执行的结果是嵌套的回调函数执行的条件
缺点:不便于阅读/不便于异常处理
解决方案:promise链式调用
终极解决:async/await
//伪代码
function successCallback(result) {
console.log('声音文件创建成功' + result)
}
function failureCallback(error) {
console.log('声音文件创建失败' + error)
}
/* 1.1 纯回调函数 */
//启动任务(audioSettings)前必须指定回调函数(callback)
createAudioFileAsync(audioSettings, successCallback, failureCallback)
/* 1.2 promise */
//可在启动任务(audioSettings)后指定回调函数(callback)
const promise = createAudioFileAsync(audioSettings)
setTimeout(() => {
promise.then(successCallback, failureCallback)
}, 1000)
/* 2.1 回调地狱 */
//回调函数的嵌套
doSomething1(function (result) {
//参数一:function(result)就是sucessCallback,接收成功的结果result
doSomethingElse2(result, function (newResult) {
doThirdThing3(newResult, function (finalResult) {
console.log('Got the final result' + finalResult)
}, failureCallback)
}, failureCallback)
}, failureCallback)
/* 2.2 promise链式调用 */
doSomething().then(function(result) {
//result是doSomething函数成功执行的返回值
return doSomethingElse(result) //执行器函数,同步回调
})
.then(function(newResult){
//newResult是doSomethingElse成功执行的返回值
return doThirdThing(newResult)
})
.then(function(finalResult){
console.log('Got the final result' + finalResult)
})
.catch(failureCallback) //统一的错误处理,上面无论哪个promise出了问题,都会到这里:异常传透
/* 2.3 async/await : 回调地狱的终极解决方案 */
//根本上去掉回调函数
async function request() {
try{