努力兑现承诺

问题描述 投票:0回答:3

我有两个功能。第一个是运行一定时间的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();
  });
}

但是这似乎没有用。我在做什么错?

javascript promise es6-promise
3个回答
0
投票

您将在drawloop的回调函数中返回Promise。

它应该可以解决问题:

const animationFunction = (args) => {
  return new Promise((resolve, reject) => {
    const duration = 1000;

    //init animation function stuff...

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

0
投票

几乎在那里,这将起作用:

const animationFunction = (args) => {
  return new Promise((resolve, reject) => {
  const duration = 1000;

  //init animation function stuff...

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

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

0
投票

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

相反,当计时器到时,从animationFunctionresolve返回一个承诺。这是一个最小的,可复制的示例:

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.