繁体   English   中英

JS Promises:为什么setTimeout回调后不能设置代码执行?

[英]JS Promises: Why is it that you can't set code to execute after the callback of setTimeout?

我正在阅读这篇关于 Javascript 中的 promise 链接的文章,并且对它说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. 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()不返回 promise 吗? 还是setTimeout在其回调完成后没有返回任何内容?

它的意思是,通过使用示例中的代码:

setTimeout(() => img.remove(), 3000); // (*)

确切地使用该代码,您无法检测到图像何时被删除并在它发生时执行某些操作 - 它的异步删除与外部 Promise 链断开连接。

修复它的文章建议是在调用.remove()时解析构造的 Promise:

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');
});

当在.then中时,要在延迟后运行下一个.then ,您必须从上述 .then 返回.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');
});

如果您不从上部.then返回 Promise ,或者如果您根本不返回任何内容,则下部.then将立即运行,只要上部.then完成,这是您不想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM