首页 > 技术文章 > JavaScript的Promise必须要会的几个点

lyzz1314 2020-09-10 09:19 原文

1. Promise.resolve()立即将Promise视为成功,立即调用then中的语句。

2. Promise.then()语句中也可以包含一个新的Promise对象。

3. Promise.catch(console.error)即可将错误抛出。

4. 除了上面一种方法外,还可以用then()中的第二个参数来处理错误。

来看下面一个例子:

const a = ()=>{
      new Promise(
            (resolve) = > {
                  setTimeout(()=>{
                        console.log('a');
                        resolve();      
                  }, 1e3
));
const b = ()=>{
      new Promise(
            (resolve) = > {
                  setTimeout(()=>{
                        console.log('b');
                        resolve();      
                  }, 1e3
));
const c = ()=>{
      new Promise(
            (resolve) = > {
                  setTimeout(()=>{
                        console.log('c');
                        reject('Oops!);      
                  }, 1e3
));
const d = ()=>{
      new Promise(
            (resolve) = > {
                  setTimeout(()=>{
                        console.log('d');
                        resolve();      
                  }, 1e3
));
// 下面开始调用
Promise.resolve()
.then(a)
.then(b)
.then(c)
.then(d)
.catch(console.error)
// 或者是下面这种捕捉错误的方式
Promise.resolve()
.then(a)
.then(b)
.then(c)
.then(d,()=>{console.log('c erred out but no big deal...')})
.catch(console.error) // 该步骤一般不会执行

如果要忽略c中发生的错误,让调用链继续执行,则可以在c所在的then中调用.catch()方法,如下:

Promise.resolve()
.then(a)
.then(b)
.then(() => {
      c().catch((error) => console.log('error ignored))
      }
)
.then(d)
.catch(console.error)

5. finally

Promise.resolve()
.then(a)
.then(b)
.then(c)
.then(d)
.catch(console.error)
.finally(()=>{console.log('always called')})

6. 最后要记住一点,Promise对象中resolve的值是不对外开放的,详情可见https://www.cnblogs.com/zxd66666/p/13394479.html,因为Promise对象的任务就是封装,最大的属性就是隔离,所以外部不能获取到内部的值,我曾困惑了一个月时间,尝试各种方法把resolve的值拿出来,最后都失败了。别信网上说的async await异步操作取值,根本取不出来。最可能的方法就是把携带返回值的Promise对象返回出来,使用时继续调用Promise的方法。

推荐阅读