首页 > 解决方案 > 努力兑现承诺

问题描述

我有两个功能。第一个是animationFunction()运行一定时间的。第二个是需要在停止循环后parentFunction()调用的函数。只能从父函数调用:dispatch()animationFunction()dispatch()

const animationFunction = (args) => {
  const duration = 1000;

  //init animation function stuff...

  //draw loop
  const loop = drawLoop(({ time }) => {
    if (time > duration) {
      loop.stop();
    }
  });
};

const parentFunction = () => {
  animationFunction(args);
  //dispatch be run after animationFunction is done looping
  dispatch(); 
}

我认为animationFunction()可以认为是异步的,因为它需要一定的时间来循环,然后程序才能继续进行。我想出了一种在循环完成dispatch()后使用回调在父函数中运行的animationFunction()方法,但我对如何使用基于 Promise 的实现感到困惑。这是我的回调解决方案:

const animationFunction = (args, callback) => {
  const duration = 1000;

  //init animation function stuff...

  //draw loop
  const loop = drawLoop(({ time }) => {
    if (time > duration) {
      loop.stop();
      callback();
    }
  });
};

const parentFunction = () => {
  animationFunction(args, () => {
    //dispatch should be run after animationFunction is done looping
    dispatch();
  }); 
}

我对Promise基于 - 的解决方案感到困惑。我试过这样做:

const animationFunction = (args) => {
  const duration = 1000;

  //init animation function stuff...

  //draw loop
  const loop = drawLoop(({ time }) => {
    if (time > duration) {
      loop.stop();
      return new Promise((resolve, reject) => {
        resolve();
      });
    }
  });
};

const parentFunction = () => {
  animationFunction(args).then(() => {
    dispatch();
  });
}

但这似乎不起作用。我究竟做错了什么?

标签: javascriptpromisees6-promise

解决方案


您不是将承诺返回给animationFunction' 调用者,而是返回drawLoop可能未处理的范围(由于大部分代码都丢失了,因此很难从您的示例中看出)。

相反,当计时器到时,从它animationFunction返回一个承诺。resolve这是一个最小的、可重现的示例:

const animationFunction = () => {
  const duration = 10;
  let ticks = 0;
  return new Promise((resolve, reject) => {
    (function update() {
      console.log(ticks++);

      if (ticks >= duration) {
        return resolve("some optional data");
      }

      requestAnimationFrame(update);
    })();
  });
};

animationFunction().then(data => {
  console.log("dispatched: " + data);
});


推荐阅读