定义
Promise是一个对象,它代表了一个异步操作的最终完成或者失败。本质上,Promise是一个被某些函数传入的对象,我们附加回调函数使用它,而不是将回调函数传入那些函数内部。
语法
new Promise( function(resolve, reject) {...} /* executor */ );
参数
executor
:executor
是带有resolve
和reject
两个参数的函数。Promise
构造函数执行时立即调用executor
函数,resolve
和reject
两个函数作为参数传递给executor
。resolve
和reject
函数被调用时,分别将Promise
的状态改为fulfilled
(完成)或者rejected
(失败)。executor
内部通常会执行一些异步操作,一旦异步操作执行完毕,要么调用resolve
函数来将promise
状态改成fulfilled
,要么调用reject
函数来将promise
状态改成rejected
。如果在executor
函数中抛出一个错误,那么该promise
状态为rejected
。executor
函数的返回值被忽略。
假设我们有一个获取用户列表的异步接口请求方法,原始的方法是使用回调函数的方式请求成功或者失败的结果
function requestSuccess(){
console.log('获取用户列表成功')
}
function requestFailure(){
console.log('获取用户列表失败')
}
requestUserList(url,requestSuccess,requestUserList)
这种情况下,我们可以使用最新的方式就是返回一个Promise,使得你可以把你的回调函数绑定在该Promise上
requestUserList(url).then(requestSuccess,requestFailure)
链式调用
连续执行两个或者多个异步操作是一个常见的需求,在上一个操作执行成功之后,开始下一个的操作,并带着上一步操作所返回的结果。
const promise = doSomething()
// .then()方法返回一个全新的promise
const newPromise = doSomething().then(successCallback,failureCallback)
回调地狱
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
通过Promise
可以解决这样的异步回调
// 使用了箭头函数
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);
错误的传递
在原先的回调地狱中,对于失败的回调需要执行多次,而在Pormise链中,只要在尾部的一个调用即可
doSomething()
.then(result => doSomethingElse(value))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(`Got the final result: ${finalResult}`))
.catch(failureCallback);
使用async和await
在使用async
和await处理异步请求的时候,需要使用try-catch
来捕获程序的异常
async function foo() {
try {
let result = await doSomething();
let newResult = await doSomethingElse(result);
let finalResult = await doThirdThing(newResult);
console.log(`Got the final result: ${finalResult}`);
} catch(error) {
failureCallback(error);
}
}