【问题标题】:JS Promises: Why is it that you can't set code to execute after the callback of setTimeout?JS Promises:为什么setTimeout回调后不能设置代码执行?
【发布时间】:2020-05-01 02:35:50
【问题描述】:

我正在阅读this article 上关于 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在回调完成后没有返回任何东西?

【问题讨论】:

  • you can't set code to execute after the callback of setTimeout? 因为它异步运行 - 在回调中做你需要的事情

标签: javascript asynchronous promise es6-promise asynchronous-javascript


【解决方案1】:

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

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 返回一个 Promise,并且该 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 完成,你不想。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多