出處: Youtube 彭彭的課程
then()接續工作
then(
function1(){成功的動作},
function2(){失敗的動作}
)
catch()接續失敗處理
catch(
function(){失敗的動作}
)
then()接續成功處理流程

then()接續成功和失敗處理流程

測試 then()
function getData(){
return new Promise(function(success,reject){ //成功和失敗
let req = new XMLHttpRequest();
req.open("get","res/javascript-");
req.onload=function(){
success(this.responseText);//成功 成功報告
};
req.onerror=function(){
reject("Error");//失敗 失敗報告
};
req.send();
});
}
//主流程
let promise=getData();
promise.then(function(result){
alert(result);//成功
},function(error){
alert(error); //失敗
});
用一個錯誤的網址試看看錯誤畫面

如果輸入正確的網址會得到以下

測試 catch()
function getData(){
return new Promise(function(success,reject){ //成功和失敗
let req = new XMLHttpRequest();
req.open("get","res/javascript-");
req.onload=function(){
success(this.responseText);//成功 成功報告
};
req.onerror=function(){
reject("Error");//失敗 失敗報告
};
req.send();
});
}
//主流程
let promise=getData();
promise.then(function(result){
alert(result);//成功
}).catch(function(error){
alert(error); //失敗
});
catch()產生的結果會和then()相同