ES6 Promise对象学习记录

ES6 Promise对象学习记录

学习网站:https://es6.ruanyifeng.com/#docs/promise, 阮一峰大大介绍ES6的博客

1.基本用法

Promise构造函数接受一个函数(function)作为参数,该函数的两个参数分别为resolve和reject,它们是两个函数,由JavaScript引擎提供。

const promise = new Promise((resolve, reject) => {
   if(/*异步操作成功*/) {
      resolve('success');//更改为resolved状态
   } 
   else {
      reject('error');//更改为rejected状态                       
   }
});

2.then方法的使用

then方法接受两个函数(function)作为参数,第一个是resolve状态下的回调函数,第二个是reject状态下的回调函数。当promise状态为resolved或rejected时,会执行相应的then方法。

//...续上面代码
promise.then(resolveValue => {
	console.log(resolveValue);//success 当promise为resolved状态    
}, error => {
    console.log(error);//error 当promise为rejected状态
});

then方法的第二个参数可以省略,并且then方法返回的是一个新的Promise对象,这意味着then方法可以嵌套使用。

promise.then(resolveValue => {
    console.log(resolveValue);//success
    return 'second success';
})
.then((value) => {
    console.log(value);//second success
});

可以看到第二个then方法中回调函数的参数接收了上一个then方法回调函数的返回值

then方法回调函数的返回值可以是一个Promise对象,这时后一个回调函数,就会等待Promise对象的状态发生变化,才会被调用。

promise.then(resolveValue => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(resolveValue);//3s后状态变为resolved,执行下一个then方法
        },3000);
    });
})
.then(value => {
    console.log(value);//success
});

3.catch方法的使用

catch方法可以捕获catch前的所有promise对象抛出的异常。

promise.then(value => {
    console.log(value + x);//这里出现了错误,因为x未定义
})
.catch(err => {
    console.log('oh no', err);//oh no ReferenceError: x is not defined
});

catch其实可以看作特殊的then方法:

promise.then(value => {
    console.log(value + x);//这里出现了错误,因为x未定义
})
.then(null, err => {
    console.log('oh no', err);//oh no ReferenceError: x is not defined
});

如果 Promise 状态已经变成resolved,再抛出错误是无法捕获的。

const promise = new Promise((resolve, reject) => {
    resolve('success');
    throw new Error('error');//此时状态已经变为resolved
 })
 .then(value => {
     console.log(value);
 })
 .catch(e => {
     console.log(e);//success
 });

先抛出异常则会捕捉到异常:

const promise = new Promise((resolve, reject) => {
    throw new Error('error');
    resolve('success');
 })
 .then(value => {
     console.log(value);
 })
 .catch(e => {
     console.log(e);//Error: error
 });

一般来说,不要在then方法里定义reject状态的回调函数(即then的第二个参数),总是使用catch方法。

// bad
promise.then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) {
    // success
  })
  .catch(function(err) {
    // error
  });

执行完catch方法指定的回调函数,会接着运行后面的then方法指定的回调函数。如果没有错误,则跳过catch方法。

promise.then(value => {
    console.log(value + x);
})
.catch(e => {
    console.log(e);// ReferenceError: x is not defined
})
.then(() => {
    console.log('go on');// go on
});

4.finally方法的使用

finally方法用于指定不管Promise对象最后的状态如何,都会执行的操作。finally方法的回调函数不接受任何参数

promise.then(result => {···})
.catch(error => {···})
.finally(() => {···});

finally本质上是then方法的特例。

promise.finally(() => {
	//some code
});

// 等同于
promise.then(result => {
	//some code
	return result;
}, error => {
	//some code
	throw error;
})

上面代码中,如果不使用finally方法,同样的语句需要为成功和失败两种情况各写一次,有了finally方法,则只需要写一次。

猜你喜欢

转载自www.cnblogs.com/hhtqwq/p/12822805.html
今日推荐