javascript - 努力兑现承诺
问题描述
我有两个功能。第一个是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();
});
}
但这似乎不起作用。我究竟做错了什么?
解决方案
您不是将承诺返回给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);
});
推荐阅读
- ietf-netmod-yang - 来自 pyang confd 的配置或操作数据
- php - 与 Gatsby 的 PHP 联系表
- python - 在短时间内求解包含积分表达式的方程
- python - Python Socket 服务器和并行定时任务
- reactjs - 带有嵌套在抽屉中的选项卡的 React Navigation v5
- groovy - 从 Groovy 中的子类调用父 trait 方法
- javascript - JQUERY:如何通过单击具有通用 JQuery 的按钮来更改输入值
- javascript - 如何用经过验证的 URL 替换简单文本?
- spring-boot - 使用动态 url 在 thymleaf 中设置背景图像
- postgresql - 使用 TSVECTOR 和特殊 UTF8 字符的 Postgres 全文搜索