Promise
Promise是什么?有什么作用?
- 異步編程的一種解決方案
- 可以將異步操作隊列化,按照期望的順序執行,返回符合預期的結果
- 可以在對象之間傳遞和操作promise,幫助我們處理隊列
Promise基本用法
promise有三種狀態:
- pending(等待態)
- fulfiled(成功態)
- rejected(失敗態)
重要:
- 狀態一旦改變,就不會再變。
- 創造Promise實例后,它會立即執行。
Promise構造函數
//Promise為一個構造器函數,可接受一個函數作為參數
const p new Promise(() => {})
//接受的這個函數也有接受兩個函數作為參數:resolve,reject(也是函數)
const p new Promise((resolve, reject) => {})
//數據處理成功
const p new Promise((resolve, reject) => {
resolve();
})
//數據處理失敗
const p new Promise((resolve, reject) => {
reject();
})
.then()
Promise執行完后.then()
。
.then()接收兩個函數作為參數
- 第一個函數式成功后調用的函數
- 第二個函數是失敗后調用的函數
- 只傳一個的話,是成功后的調用
const p new Promise(() => {})
p.then(()=>{},()=>{})
示例.then()
//成功
const p new Promise((resolve, reject) => {
reject("成功了");
})
p.then(value=>{
console.log(value); //成功了
})
//失敗
const p new Promise((resolve, reject) => {
reject("失敗了");
})
p.then(value=>{
console.log(value);
},err=>{
console.log(err); //失敗了
})
.then()的返回值也是一個Promise對象
const t = p.then()
// t 是一個Promise對象
.then返回一個Promise對象,這樣就可以實現鏈式調用
const p new Promise(() => {}).then().then().then().then()
在.then()中使用return可以操作返回的Promise對象
const p new Promise((resolve, reject) => {
$.ajax({
type: 'GET',
url: 'www.baidu.com/getxxxx',
success: res => {
resolve(res);//成功
}
})
})
.then(value=>{
console.log(value); //成功了
/* return的東西可被下一個then接受到 */
return new Promise((resolve, reject) => {
$.ajax({
type: 'GET',
url: 'www.baidu.com/getxxxx',
success: res => {
resolve(res);//成功
}
})
})
})
.then().then()
/* 相同的代碼可封裝成函數 */
.catch
錯誤處理
const p new Promise((resolve, reject) => {
reject();
})
p.then().then().catch()
.all()
Promise.all([p1, p2, p3])用於將多個promise實例,包裝成一個新的Promise實例,返回的實例就是普通的promise。
它接收一個數組作為參數,數組里可以是Promise對象,也可以是別的值,只有Promise會等待狀態改變,當所有的子Promise都完成,該Promise完成,返回值是全部值得數組,有任何一個失敗,該Promise失敗,返回值是第一個失敗的子Promise結果
.race()
類似於.all()
,區別在於它有任意一個完成就算完成