zoukankan      html  css  js  c++  java
  • JavaScript的Promise必须要会的几个点

    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的方法。

  • 相关阅读:
    排列专题(不定期更新)
    搜索专题(不定期更新)
    Redis 高级面试题
    面试题1
    CentOS7查看开放端口命令及开放端口号
    Union和Union All到底有什么区别
    浅谈MySQL中优化sql语句查询常用的30种方法
    什么是分布式系统,如何学习分布式系统(转)
    浅析分布式系统(转)
    什么是分布式系统(通俗易懂的说法)(转)
  • 原文地址:https://www.cnblogs.com/lyzz1314/p/13643913.html
Copyright © 2011-2022 走看看