我有两个功能。第一个是运行一定时间的 animationFunction()
。第二个是 parentFunction()
,它需要在 animationFunction()
停止循环后运行一个名为 dispatch()
的函数。 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();
});
}
但这似乎不起作用。我做错了什么?
最佳答案
您不会将 promise 返回给 animationFunction
的调用者,而是返回给可能未处理的 drawLoop
范围(很难从您的示例中看出,因为大多数代码丢失)。
相反,从 animationFunction
返回一个 promise ,并在计时器到时解决
它。这是一个最小的、可重现的示例:
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);
});
关于javascript - 努力实现 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61534648/