【JS學習】js中 then、catch、finally


1、 Promise 的狀態一經改變就不能改變,也就是說一個Promise實例執行后只有一個狀態,要么是resolve, 要么是reject 。

resolve或reject后遇到reject或resolve會忽略該代碼不執行。

但是其他代碼仍然會執行。

復制代碼
var promise = new Promise((resolve, reject) => {
  resolve("success1");
  console.log('123');
  reject("error");
  console.log('456');
  resolve("success2");
});

promise
.then(res => {
    console.log("then: ", res);
  }).catch(err => {
    console.log("catch: ", err);
  })
復制代碼

運行結果:

123
456
then: success1

 

2、then 、 catch 、 finally 都會返回一個新的 promise, 所以可以鏈式調用。

Promise中,返回任意一個非 promise 的值都會被包裹成 promise 對象,

例如 return 'hehe' 會被包裝為return Promise.resolve('hehe')

return 的值只會往下傳給 then,無論中間是否有catch 或者 finally。

復制代碼
var promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("success1");
  }, 1000)
});

promise
.then(res => {
    console.log("then: ", res);
    return 'bibi';
  }).catch(err => {
    console.log("catch: ", err);
    return 'err';
  }).finally((fin)=> {
    console.log(fin);
    console.log('final');
    return 'haha';
  }).then((res) => {
    console.log(res);
    console.log('final-after')
  }).then((res) => {
    console.log(res);
    console.log('final-after2')
  })
復制代碼

運行結果:

then: success1
undefined
final
bibi
final-after
undefined
final-after2

 

3、catch 可以捕捉上層錯誤,但是對下層錯誤是捕捉不到的。

復制代碼
var promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("error");
  }, 1000)
});

promise
.then(res => {
    console.log("then: ", res);
    return 'bibi';
  }).catch(err => {
    console.log("catch: ", err);
    return 'err'; // 這里返回了一個 Promise
  }).then((res)=> { // 繼續執行
    console.log('then2', res);
    return Promise.reject('error2');
  }).catch((err) => { //捕捉上層錯誤,可以隔層捕捉,但是捕捉過的錯誤不能再捕捉
    console.log('catch2', err);
  })
復制代碼

運行結果:

catch: error
then2 err
catch2 error2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM