【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

posted @ 2022-01-22 16:53  gtea  阅读(7363)  评论(0编辑  收藏  举报