• JavaScript 里的 Promise Chaining


    Promise 通常被定义为最终将可用的值的代理(proxy)。

    问题背景

    回调:我们有一系列异步任务要一个接一个地执行——例如,加载脚本。 我们怎样才能很好地编码呢?

    Promise 提供了一些方法来做到这一点:Promise 链。

    它看起来像这样:

    new Promise(function(resolve, reject) {
    
      setTimeout(() => resolve(1), 1000); // (*)
    
    }).then(function(result) { // (**)
    
      alert(result); // 1
      return result * 2;
    
    }).then(function(result) { // (***)
    
      alert(result); // 2
      return result * 2;
    
    }).then(function(result) {
    
      alert(result); // 4
      return result * 2;
    
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    这个思路是结果通过 .then 处理程序链传递。

    其流程是:

    • 初始 promise 在 1 秒内 resolve (*)
    • 然后调用 .then 处理程序,then 方法返回一个新创建的 Promise(以 2 值解析)。
    • 下一个 then 获取前一个的结果,对其进行处理(加倍)并将其传递给下一个处理程序。
      以此类推。

    切记,每次调用 .then 都会返回一个新的 Promise,这样我们就可以调用下一个 .then 了。

    当处理程序返回一个值时,它成为该 Promise 的结果,因此下一个 .then 被调用。

    初学者经常犯的错误,对同一个 promise 对象反复调用 then 方法。这并不是 Promise 的链式调用。

    let promise = new Promise(function(resolve, reject) {
      setTimeout(() => resolve(1), 1000);
    });
    
    promise.then(function(result) {
      alert(result); // 1
      return result * 2;
    });
    
    promise.then(function(result) {
      alert(result); // 1
      return result * 2;
    });
    
    promise.then(function(result) {
      alert(result); // 1
      return result * 2;
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    我们在这里所做的只是对一个 Promise 的几个处理程序。 他们不会将结果传递给对方; 相反,他们独立处理它。

    所有 .then 在同一个 Promise 上得到相同的结果——那个 Promise 的结果。 所以在上面的代码中所有 alert 显示相同值:1。

    在实践中,我们很少需要多个处理程序来处理一个 Promise。 chaining 调用的使用频率更高。

  • 相关阅读:
    Linux:按时间批量删除文件(删除N天前文件)
    Pluck 代码问题漏洞( CVE-2022-26965)
    python7
    HTC使用官方固件作为底包制作rom卡刷包教程
    [CMD]常用命令
    page、request、session和application有什么区别?以及cookie的含义
    SVC服务的发现
    2.15 OrCAD中怎么创建带图片的Title Block?【OrCAD原理图封装库50问解析】
    要月入百亿!李想的理想能否实现?
    德克萨斯大学奥斯汀分校自然语言处理硕士课程汉化版(第四周) - 语言建模
  • 原文地址:https://blog.csdn.net/i042416/article/details/126304948