javascript - JS Promises:为什么setTimeout回调后不能设置代码执行?
问题描述
我正在阅读这篇关于 Javascript 中的承诺链的文章,并且对它所说的部分感到困惑how can we do something after the avatar has finished showing and gets removed? For instance, we’d like to show a form for editing that user or something else. As of now, there’s no way.
图像被删除后我们不能做某事的原因是img.remove()
不是没有返回承诺?还是setTimeout
在回调完成后不返回任何内容?
解决方案
它的意思是,通过使用示例中的代码:
setTimeout(() => img.remove(), 3000); // (*)
准确地使用该代码,您无法检测图像何时被删除并在它发生时执行某些操作 - 它的异步删除与外部 Promise 链断开连接。
修复它的文章建议是让构造的 Promise 在.remove()
被调用时解析:
setTimeout(() => {
img.remove();
resolve(githubUser);
}, 3000);
或者您可以将更多代码放入其中,setTimeout
以便在图像被删除时准确运行。
setTimeout(() => {
img.remove();
console.log('removed');
}, 3000);
如果您不执行上述任何一项,而只有,则setTimeout(() => img.remove(), 3000);
3 秒后发生的异步操作除了删除图像外无法执行任何操作 - 这通常是一个错误。例如,如果您想将另一个链接.then
到它,它会在图像被删除时运行,并且图像需要在 3 秒后被删除
.then(() => {
// what logic to put in here to ensure next .then runs after 3 seconds?
setTimeout(() => {
img.remove();
}, 3000);
})
.then(() => {
console.log('image removed');
});
在 a.then
中时,要.then
在延迟后进行下一次运行,您必须从上述返回一个 Promise .then
,并且该 Promise 必须在延迟结束后解析。
.then(() => {
// what logic to put in here to ensure next .then runs after 3 seconds?
return new Promise((resolve) => {
setTimeout(() => {
img.remove();
}, 3000);
});
.then(() => {
console.log('image removed');
});
如果你没有从上层返回一个 Promise .then
,或者你根本不返回任何东西,下层.then
将立即运行,一旦上层.then
完成,这是你不想要的。
推荐阅读
- powerbuilder - 无法删除 PowerBuilder 对象
- android - 使用 FFmpeg 进行视频压缩
- core-graphics - 使用 Core Graphics 使用 AppleScriptObjC 更改图像色彩空间配置文件
- python - 从 SublimeText3 SublimeREPL 包运行时未激活 Anaconda Python 环境
- javascript - 如何在 jhipster 应用程序中正确导入传单,运行 webpack?- 标记图标丢失
- python - 解决文本重叠的最佳方法是什么?
- javascript - 网页加载后,我想使用 webview 使用 android java 代码选择网页的单选按钮
- mongodb - Spring Data MongoDB 并发更新行为
- python - 如何将 xticks 更改为特定范围
- html - 在 Excel VBA 中使用 getElementsBy??Name