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

  • 相关阅读:
    uva10986 堆优化单源最短路径(pas)
    动态规划②——线性动态规划(背包)
    UVA567
    动态规划①——记忆化搜索
    网络号与主机号的区分与计算(转)
    故障处理-ORA-00376/ORA-01110
    Oracle的自动统计信息不收集直方图的信息
    Oracle 11g的Redo Log和Archive Log的分析方法
    SQL优化 1
    oracle 11g 通过在线重定义方式修改表结构
  • 原文地址:https://www.cnblogs.com/lyzz1314/p/13643913.html
Copyright © 2011-2022 走看看