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

  • 相关阅读:
    常用AJAX框架
    ASP.NET Mvc Preview 5 演示Demo #4 实现RadioButtonList与DropDownList应用
    ASP.NET MVC 中的数据分页(三
    扩展方法(1) DataTable 和List 相互转换
    服务器端压缩发送数据到客户端ASP.NET MVC
    ASP.NET MVC 中的数据分页(四)
    msdn DataList Web 服务器控件概述
    msdn ASP.NET 演练精选
    msdn ASP.NET 主题和外观
    msdn 数据 Web 服务器 (ASP.NET) 控件
  • 原文地址:https://www.cnblogs.com/lyzz1314/p/13643913.html
Copyright © 2011-2022 走看看