代码之家  ›  专栏  ›  技术社区  ›  Audun Olsen

在事件上开始提取,但要等到它本身和另一个承诺解决后——JavaScript

  •  0
  • Audun Olsen  · 技术社区  · 7 年前

    我正在制定一个组织结构图。我在寻找重组的技巧,我如何处理两个es6的承诺,为一个小的性能增益。

    1. 播放第一部动画(承诺)
    2. 获取所有数据(承诺)
    3. 播放最后一个动画

    理想情况下,我希望:

    1. 开始提取数据
    2. 播放最后一个动画(需要提取的数据,但无法在第一个动画结束前播放)

    以下是相关代码:

    /* Click happened! */
    
    orgWrap.shiftRow({ row: clickY, from: clickX, to: focusX }).then(() => {
        /* Shiftrow is a promise triggering an animation,
           it resolved on 'transitionend' */
    
        fetch(`api/org/${target.id}/1`).then(result =>  {
            /* a function placing result in the DOM runs
               After data finished loading */
    
            orgWrap.populateRow({ data: result.children, row: clickY+1 });
            /* The animation which plays last, when shiftRow and fetch has settled */
      });
    
    });
    

    就目前情况而言,这两项工作之间偶尔会有不必要的延误 shiftRow 和 populateRow

    3 回复  |  直到 7 年前
        1
  •  2
  •   Georgy    7 年前

    你可以用 Promise.all() 前两个承诺,, then 第三个。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

        2
  •  1
  •   zero298    7 年前

    将提取和开始动画包装在 Promise.all() 并在结束后运行结束动画 Promise.all

    因此:

    async function animate() {
      // some animation logic
    }
    
    Promise
      .all([
        animate(), // Beginning animation
        fetch("some.html")
      ])
      .then([, neededFetchData] => {
        return animate(neededFetchData);
      });
    
        3
  •  1
  •   Bergi    7 年前

    你会想用 Promise.all 为此:

    /* Click happened! */
    
    Promise.all([
      orgWrap.shiftRow({ row: clickY, from: clickX, to: focusX }), // Shiftrow is a promise triggering an animation, it resolved on 'transitionend'
      fetch(`api/org/${target.id}/1`),
    ]).then(([animationResult, fetchResult]) => {
      /* a function placing result in the DOM runs after data finished loading */
    
      return orgWrap.populateRow({ data: result.children, row: clickY+1 }); // The animation which plays last, when shiftRow and fetch has settled
    });
    

    还要确保 chain your promise callbacks instead of unnecessarily nesting them .