loadAsync1()
.then(function(data1) {
return loadAsync2(data1)
})
.then(function(data2){
return loadAsync3(data2)
})
.then(okFn, failFn)
******************* *****************
loadAsync1()
.then(function(data1) {
loadAsync2(data1)
})
.then(function(data2){
loadAsync3(data2)
})
.then(res=>console.log(res))
複製代碼
不等同狀況,此時catch捕獲並非ajaxLoad1錯誤 而是ajaxLoad2的錯誤。**看場景有時要結合起來使用**
```js
ajaxLoad1()
.then(res=>{ return ajaxLoad2() })
.catch(err=> console.log(err))
----------------------
// 結合使用
ajaxLoad1()
.then(res=>{ return ajaxLoad2() }, err=>console.log(err))
.catch(err=> console.log(err))
```
複製代碼
若是then或catch接收的不是函數,那麼就會發生穿透行爲,因此在應用過程當中,應該保證then接收到的參數始終是一個函數ajax
new Promise(resolve=>resolve(8))
.then(1)
.catch(null)
.then(Promise.resolve(9))
.then(res=> console.log(res))
// 8
複製代碼
// 0 未初始化未調用open
// 1.啓動 調用open 未調用 send
// 2. 發送 已調用send() 可是未響應
// 3. 接收 已經接收部分響應數據
// 4.完成 完成所有數據響應
const ajax = function (params) {
if (!params.url) return
const promise = new Promise((resolve, reject) => {
const handler = function () {
if (this.readyState !== 4) return
if (this.status == 200) {
try {
let resonse = JSON.parse(this.responseText)
resolve(resonse)
} catch (error) {
reject(error)
}
} else {
reject(new Error(this.statusText))
}
}
const xhr = new XMLHttpRequest()
if (params.method.toLowerCase() == 'get') {
xhr.open('get', url + '?' + formatParams(params.data));
xhr.send()
} else {
xhr.open('post', url);
xhr.send(JSON.stringify(params.data));
}
xhr.onreadystatechange = handler
xhr.responseType = 'json'
xhr.setRequestHeader('Accept', 'application/json');
})
return promise
function formatParams(obj) {
if (!data) return
var arr = []
for (let i in obj) {
arr.push(`${encodeURIComponent(i)}=${encodeURIComponent(obj[i])}`)
}
return arr.join('&')
}
}
複製代碼
- promise.then(onFulfilled, onRejected)
在onFulfilled中發生異常的話,在onRejected中是捕獲不到這個異常的。
- promise.then(onFulfilled).catch(onRejected)
.then中產生的異常能在.catch中捕獲
複製代碼
```JS
/* 例4.1 */
function taskA() {
console.log(x);
console.log("Task A");
}
function taskB() {
console.log("Task B");
}
function onRejected(error) {
console.log("Catch Error: A or B", error);
}
function finalTask() {
console.log("Final Task");
}
var promise = Promise.resolve();
promise
.then(taskA) // 拋出錯誤,不繼續Task A」
.then(taskB) // .then沒有捕獲A拋出的錯,不打印 「Task B」
.catch(onRejected) // 捕獲了A的錯,打印錯誤信息
.then(finalTask); // 錯誤已經被捕獲,執行resolve
-------output-------
Catch Error: A or B,ReferenceError: x is not defined
Final Task
```
複製代碼
```JS
//方法1:對同一個promise對象同時調用 then 方法
var p1 = new Promise(function (resolve) {
resolve(100);
});
p1.then(function (value) {
return value * 2;
});
p1.then(function (value) {
return value * 2;
});
p1.then(function (value) {
console.log("finally: " + value);
});
-------output-------
finally: 100
------------------------------------------------------
//方法2:對 then 進行 promise chain 方式進行調用
var p2 = new Promise(function (resolve) {
resolve(100);
});
p2.then(function (value) {
return value * 2;
}).then(function (value) {
return value * 2;
}).then(function (value) {
console.log("finally: " + value);
});
-------output-------
finally: 400
```
複製代碼
```JS
// Errors thrown inside asynchronous functions will act like uncaught errors
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
throw 'Uncaught Exception!';
}, 1000);
});
promise.catch(function(e) {
console.log(e); //This is never called
});
```複製代碼